在将图像循环作为 div 背景之前加载图像?

发布于 2024-10-04 22:02:45 字数 723 浏览 5 评论 0原文

我有一个使用 CSS 在 php 中开发的标准网页,目前使用一些 javascript 来循环浏览优惠 div 的一些图像。您可以在此处查看该网站,这不是它的最终安息地,这是一个临时网站。如果您查看优惠横幅。当它切换到下一个图像时,它会在加载下一个图像时变白。在将下一张图像应用到 div 背景属性之前是否有加载该图像的方法? 这是我的 javascript atm。

var c=0
var s
function offersCycle()
{
  if (c%3==0){
  document.getElementById('offers').style.background = "url(/images/1.jpg)";
}
if (c%3==1){
  document.getElementById('offers').style.background = "url(/images/2.jpg)";
}
if (c%3==2){
  document.getElementById('offers').style.background = "url(/images/3.jpg)";
}
c=c+1
s=setTimeout("offersCycle()",8000)

我尝试在 javascript 中使用一组新图像并在循环它们之前定义它们,但它们不适用于 CSS,因为这依赖于 url 而不是图像本身?任何想法表示赞赏。 干杯, 约旦

I have a standard webpage developed in php using CSS and currently a bit of javascript to cycle through some images for a offers div. You can see the site here, this will not be it's final resting place this is a temporary site. If you look at the offers banner. When it switches to the next image it goes white whilst it loads the next image. Is there anyway of loading the next image before applying it to the div background property?
Here is my javascript atm.

var c=0
var s
function offersCycle()
{
  if (c%3==0){
  document.getElementById('offers').style.background = "url(/images/1.jpg)";
}
if (c%3==1){
  document.getElementById('offers').style.background = "url(/images/2.jpg)";
}
if (c%3==2){
  document.getElementById('offers').style.background = "url(/images/3.jpg)";
}
c=c+1
s=setTimeout("offersCycle()",8000)

I tried using a set of new Images in the javascript and defining them before cycling them but they wouldn't apply to the CSS as this relies on a url and not an image itself? Any ideas appreciated.
Cheers,
Jordan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨离汐 2024-10-11 22:02:45

我会做这样的事情:

var c = 0, images = ["/images/1.jpg", "/images/2.jpg", "/images/3.jpg"];
for(var i=0; i<images.length; i++) {
  var img = new Image();
  img.src = images[i];
}
function offersCycle() {
  document.getElementById('offers').style.background = "url("+images[c%images.length]+")";
  c++;
}
var s = setTimeout(offersCycle, 8000);

通过使用数组,我们简化了逻辑,并且可以使用相同的数组来预加载图像,以便在页面首次加载时缓存它们。这还允许您向数组中添加任意数量的图像,而无需进行任何更改。

I would do something like this:

var c = 0, images = ["/images/1.jpg", "/images/2.jpg", "/images/3.jpg"];
for(var i=0; i<images.length; i++) {
  var img = new Image();
  img.src = images[i];
}
function offersCycle() {
  document.getElementById('offers').style.background = "url("+images[c%images.length]+")";
  c++;
}
var s = setTimeout(offersCycle, 8000);

By using an array, we simplify the logic and can use the same array to preload the images to cache them when the page first loads. This also allows you to add as many images as you want to the array without changing anything.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文