开发者

Cycle css backgrounds

Hey, I'm just wondering how to cycle through a bunch of images, and set them as the background for a div.

What I'm looking to do is: set the first image as the background to开发者_JAVA技巧 a div. Wait X seconds. Set the next image as the background. Wait X seconds … etc. and continue

I've got the following code which works for 1 image.

$(document).ready(function() {
  var source = $(".field-field-background img:first").attr("src");
  $('.field-field-background img:first').remove();
  $('#main-inner').css('background', 'url('+ source +') no-repeat');
});

I'm guessing I need to get an array of the image sources, loop through the array and set it as the background, with a delay somewhere in the loop. Any ideas how I'd do this?


One of the biggest advantages of jQuery is that it has a very robust plug-in community. Many tasks that you might want to accomplished have been tackled by others before you. Particularly with a common task like this, I would recommend looking for a plug-in first, before trying to reinvent the wheel. Many plug-ins have the advantage of having gone through rigorous testing and multiple versions, to result in a polished product.

The jQuery Cycle plug-in would be a good candidate, if you are looking to do a slideshow type effect. If what you want is to cycle the background, while keeping foreground elements, you might look at something more like this: Advanced jQuery background image slideshow


$(document).ready(function() {
  Cycler={};
  Cycler.src=['path/to/img1', 'path/to/img2', 'path/to/img3'];
  Cycler.cur=0;
  Cycler.cycle=function() {
    if(++Cycler.cur>=Cycler.src.length) {
      Cycler.cur=0;
    }

    $('#main-inner').css('background', 'url('+ Cycler.src[Cycler.cur] +') no-repeat');
    setTimeout(Cycler.cycle, 5000);//5 seconds
  }

  Cycler.cycle();
});


try this:

setInterval(function(){
    var source = $(".field-field-background img:first").attr("src");
    $('.field-field-background img:first').remove();
    $('#main-inner').css('background', 'url('+ source +') no-repeat');
},4000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜