开发者

jquery $('body') image swap help

I have the code below:

    $(document).ready(function() {
 开发者_StackOverflow社区 var bgimages=new Array()
  bgImages[0]="bg.jpg"
  bgImages[1]="bg2.jpg"
  //sloppy preload images
  var pathToImg=new Array()
  for (i=0;i<bgImages.length;i++)
  {
    pathToImg[i]=new Image()
    pathToImg[i].src=bgImages[i]
  }

  var i = 0;
  var rotateBg = setInterval(
  function(){
    $('body').css({backgroundImage:'url(' + bgImages[i] + ')'});
      i++;
   }, 9000);
});

I need assistance solving 2 issues:

  1. It will only loop through the images once, what am I missing? I would like it to repeat endlessly.
  2. How can I cross fade the images in?


You need to ensure you don't index beyond the upper bound of your array.

In your case, a simple bitwise XOR does the job:

i ^= 1;

If you had more elements in your array, a modulo op would do the job:

i++; i %= bgImages.length;

For the crossfade, you might want to consider CSS transitions. There is even an example on the page. However, this is a W3C working draft, and currently only Webkit-based browsers support it. Firefox should support it before end of year. No words on whether IE will support it and when. Nice thing is it's pretty simple to create, no JS required.

Excerpt:

<style type="text/css">
div.fader img { -webkit-transition: all 1s ease-in-out; }
img.swap1, div.fader:hover img.swap2 { opacity: 1.0; }
div.fader:hover img.swap1, img.swap2 { opacity: 0; }
</style>


you can try

function(){
i=i<bgImages.length?i:0;
$('body').css({backgroundImage:'url(' + bgImages[i] + ')'});
      i++;
   }
}

this will reset i to 0 each time it has reached the end of the array

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜