如何通过几个图像循环div的background-url?

时间:2022-08-08 20:12:12

I've read through a few similar questions but can't find an answer to my specific problem.

我已经阅读了一些类似的问题,但找不到我的具体问题的答案。

My html is:

我的HTML是:

<div id="top-area">
  <div class="container">

    // Show title of website here

  </div>
</div>

My css is: #top-area { background-image: url("http://example.com/images/bg.jpg"); }

我的css是:#top-area {background-image:url(“http://example.com/images/bg.jpg”); }

I would like to have the background of my div fade between up to 5 images.

我希望我的div的背景可以在最多5张图像之间淡出。

I've tried defining a #top-area2 and #top-area3 in css and then doing this in jQuery:

我已经尝试在css中定义#top-area2和#top-area3,然后在jQuery中执行此操作:

$("#top-area").attr("id","top-area2");

But that doesn't give the effect I'm looking for. All the other examples I've found seem to point towards filling the div with hidden images and then revealing them one by one but this doesn't give me the background-image behaviour I'm looking for.

但这并没有给我正在寻找的效果。我发现的所有其他例子似乎都指向用隐藏的图像填充div然后逐个显示它们但这并没有给我我正在寻找的背景图像行为。

Is this possible? Thanks.

这可能吗?谢谢。

2 个解决方案

#1


This will crossfade and cycle through an array of images:

这将交叉淡入淡出并循环显示一系列图像:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'],
    index  = 0,
    $top   = $('#top-area');

setInterval(function() {
   $top.animate({ opacity: 0 }, 500, function() {
     $top.css('background-image', 'url('+images[++index]+')');
     $top.animate({ opacity: 1 }, 500, function() {
       if(index === images.length) index = 0;
     });
   });
}, 6000);

Demo

#2


I'd put the image URLs in an array:

我将图像URL放在一个数组中:

var backgrounds = [
   '/img-one.jpg',
   '/img-two.jpg',
   ... 
];
var i = 0;

Then use an interval function to loop through them, updating the CSS:

然后使用interval函数循环遍历它们,更新CSS:

setInterval(function() {
    $('#top-area').css('background-image', 'url(' + backgrounds[i] + ')');

    i++;

    if (i == backgrounds.length) {
        i = 0;
    }
}, 1000);

#1


This will crossfade and cycle through an array of images:

这将交叉淡入淡出并循环显示一系列图像:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg'],
    index  = 0,
    $top   = $('#top-area');

setInterval(function() {
   $top.animate({ opacity: 0 }, 500, function() {
     $top.css('background-image', 'url('+images[++index]+')');
     $top.animate({ opacity: 1 }, 500, function() {
       if(index === images.length) index = 0;
     });
   });
}, 6000);

Demo

#2


I'd put the image URLs in an array:

我将图像URL放在一个数组中:

var backgrounds = [
   '/img-one.jpg',
   '/img-two.jpg',
   ... 
];
var i = 0;

Then use an interval function to loop through them, updating the CSS:

然后使用interval函数循环遍历它们,更新CSS:

setInterval(function() {
    $('#top-area').css('background-image', 'url(' + backgrounds[i] + ')');

    i++;

    if (i == backgrounds.length) {
        i = 0;
    }
}, 1000);