我正在构建一个循环显示 3 种不同背景的页面,每 750 毫秒更改一次。为此,我将使用相关背景图像向正文中添加一个类,并使用 JS 进行更改。对于第一个循环,它们会闪烁,因为图像必须加载,所以它不会立即出现。因此,有什么方法可以用来预加载图像吗?
CSS:
&.backgrounds{
background-position: center bottom;
background-repeat: no-repeat;
background-size: 130%;
&.freddy{
background-image: url(/img/illustrations/snapchat/snapchat_holding_page_freddy.jpg);
}
&.irene{
background-image: url(/img/illustrations/snapchat/snapchat_holding_page_irene.jpg);
}
&.joe{
background-image: url(/img/illustrations/snapchat/snapchat_holding_page_joe.jpg);
}
}
JS:
setInterval(function() {
if ( $('.backgrounds').hasClass('freddy') ){
$('.backgrounds').removeClass('freddy').addClass('irene');
} else if ( $('.backgrounds').hasClass('irene') ){
$('.backgrounds').removeClass('irene').addClass('joe');
} else if ( $('.backgrounds').hasClass('joe') ){
$('.backgrounds').removeClass('joe').addClass('freddy');
}
}, 750);
最佳答案
我会做这样的事情。 loadImages 返回一个 Promise,一旦所有图像都加载完毕,该 Promise 就会解析。附加到它的 .then 调用 cycleImages,它启动间隔。因为无论如何你都需要 JS 中的 URL 来进行预加载,而不是类切换我直接操作 background-image,这样你就可以从 CSS 中删除图像 URLs 和保存一些冗余字节。这也使得将来扩展图像列表也变得更加容易,您只需要将一个元素添加到图像数组中,而无需维护复杂的 if 语句。
function loadImages (images) {
// each image will be loaded by this function.
// it returns a Promise that will resolve once
// the image has finished loading
let loader = function (src) {
return new Promise(function (resolve, reject) {
let img = new Image();
img.onload = function () {
// resolve the promise with our url so it is
// returned in the result of Promise.all
resolve(src);
};
img.onerror = function (err) {
reject(err);
};
img.src = src;
});
};
// create an image loader for each url
let loaders = [];
images.forEach(function (image) {
loaders.push(loader(image));
});
// Promise.all will return a promise that will resolve once all of of our
// image loader promises resolve
return Promise.all(loaders);
}
// the images we are going to display
let myImages = [
'http://www.gifpng.com/400x200',
'http://www.gifpng.com/400x200/ffffff/000000',
'http://www.gifpng.com/400x200/000000/ffffff'
];
// $(document).ready(fn) is deprecated,
// use the $(fn) form instead
$(function() {
// after the images are loaded this will be called with an array of the loaded images
function cycleImages (images) {
let index = 0;
setInterval(function() {
// since we need an array of the image names to preload them anyway,
// just load them via JS instead of class switching so you can cut them
// out of the CSS and save some space by not being redundant
$('#backgrounds').css('backgroundImage', 'url("' + images[index] + '")');
// increment, roll over to 0 if at length after increment
index = (index + 1) % images.length;
}, 750);
}
// load the images and start cycling through them after they are loaded
loadImages(myImages).then(cycleImages).catch(function (err) {
console.error(err);
});
});#backgrounds {
height: 200px;
width: 400px;
border: 1px solid #000;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="backgrounds"></div>
编辑:
以Just a student考虑到评论,这里有一个版本,它只会在加载图像后切换图像,但如果加载了图像,则立即执行。它还会跳过加载失败的图像。由于 cycleImages 不再通过 .then 调用,我也对其进行了更改,使其接受目标元素(作为 jQuery 对象)以及一组图像 promise 。这样一来,您可以根据需要在具有不同图像集的页面上的多个位置轻松使用它。
function loadImages (images) {
// each image will be loaded by this function.
// it returns a Promise that will resolve once
// the image has finished loading
let loader = function (src) {
return new Promise(function (resolve, reject) {
let img = new Image();
img.onload = function () {
// resolve the promise with our url
resolve(src);
};
img.onerror = function (err) {
reject(err);
};
img.src = src;
});
};
// return an array of image-loading promises
return images.map(function (image) {
return loader(image);
});
}
// the images we are going to display
let myImages = [
'http://www.gifpng.com/400x200',
'http://www.invalid-domain-name.foo/this-url-certainly-does-not-exist.jpg',
'http://www.gifpng.com/400x200/ffffff/000000',
'http://www.gifpng.com/400x200/000000/ffffff'
];
// $(document).ready(fn) is deprecated,
// use the $(fn) form instead
$(function() {
// this receives an array of the promises for each image
function cycleImages ($target, images) {
let index = 0,
interval = 750; // how many ms to wait before attempting to switch images
function nextImage () {
// p is the promise for the current image
let p = images[index],
next = function (wait) {
// increment our counter and wait to display the next one
index = (index + 1) % images.length;
setTimeout(nextImage, wait);
};
// wait for this image to load or fail to load
p.then(function (src) {
// it loaded, display it
$target.css('backgroundImage', 'url("' + src + '")');
next(interval);
}).catch(function (err) {
// this one failed to load, skip it
next(0);
});
}
// start cycling
nextImage();
}
// load the images and start cycling through them as they are loaded
cycleImages($('#backgrounds'), loadImages(myImages));
});#backgrounds {
height: 200px;
width: 400px;
border: 1px solid #000;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="backgrounds"></div>
除了硬编码图像更改之间的间隔,您还可以将其作为参数传递。不过在那时,我会重构它以使用配置对象来传递除图像 promise 数组之外的所有内容:cycleImages(myImages, {target: $('#backgrounds'), interval: 1000});
关于javascript - 预加载背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42998327/
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
我有一张背景图片,我想在其中添加一个文本框。我想弄清楚如何将标题放置在其顶部的正确位置。(我使用标题是因为我需要自动换行功能)。现在,我只能让文本显示在左上角,但我需要能够手动定位它的开始位置。require'RMagick'require'Pry'includeMagicktext="Loremipsumdolorsitamet"img=ImageList.new('template001.jpg')img 最佳答案 这是使用convert的ImageMagick命令行的答案。如果你想在Rmagick中使用这个方法,你必须自己移植
我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数
我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co
我们目前正在为ROR3.2开发自定义cms引擎。在这个过程中,我们希望成为我们的rails应用程序中的一等公民的几个类类型起源,这意味着它们应该驻留在应用程序的app文件夹下,它是插件。目前我们有以下类型:数据源数据类型查看我在app文件夹下创建了多个目录来保存这些:应用/数据源应用/数据类型应用/View更多类型将随之而来,我有点担心应用程序文件夹被这么多目录污染。因此,我想将它们移动到一个子目录/模块中,该子目录/模块包含cms定义的所有类型。所有类都应位于MyCms命名空间内,目录布局应如下所示:应用程序/my_cms/data_source应用程序/my_cms/data_ty
我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的
如何只加载map边界内的标记gmaps4rails?当然,在平移和/或缩放后加载新的。与此直接相关的是,如何获取map的当前边界和缩放级别? 最佳答案 我是这样做的,我只在用户完成平移或缩放后替换标记,如果您需要不同的行为,请使用不同的事件监听器:在你看来(index.html.erb):{"zoom"=>15,"auto_adjust"=>false,"detect_location"=>true,"center_on_user"=>true}},false,true)%>在View的底部添加:functiongmaps4rail
我正在尝试找出一种方法来显示来自不在RAILS_ROOT下(在RedHat或Ubuntu环境中)的已安装文件系统的图像。我不想使用符号链接(symboliclink),因为这个应用程序实际上是通过Tomcat部署的,而当我关闭Tomcat时,Tomcat会尝试跟随符号链接(symboliclink)并删除挂载中的所有图像。由于这些文件的数量和大小,将图像放在public/images下也不是一种选择。我查看了send_file,但它只会显示一张图片。我需要在一个格式良好的页面中显示6个请求的图像。由于膨胀,我宁愿不使用Base64编码,但我不知道如何将图像数据与呈现的页面一起传递下去。