在JQuery中循环显示背景图像

时间:2011-07-19 04:51:17

标签: jquery fade jquery-cycle

基本上我需要的是一种每5秒更改一次页面背景图像并具有淡入淡出效果的简单方法。我遇到的问题是我想用我的主体标签做这个,我有这个CSS:

body {
  background: url("images/bg-home.jpg") no-repeat scroll center top #000000;
}

因此循环需要将此div更改为bg-home-1.jpg,bg-home-2.jpg等等......这必须是动态的,因为每个页面都有不同数量的图像所以我< strong>不能使用这种方式:

  <div id="fading-images"> 
    <img src="img/home-1.jpg"> 
    <img src="img/home-2.jpg"> 
    <img src="img/home-3.jpg"> 
      </div> 
setInterval(function(){
    $('#fading-images:first-child').fadeOut('slow')
     .next('img').fadeIn('slow')
     .end().appendTo('#slideshow');}, 
     4000);

}

希望有人可以帮助我:)。

1 个答案:

答案 0 :(得分:3)

小提琴:http://jsfiddle.net/G3Fyv/3/

HTML:

<html>
    <body>
        <div id="fader"></div>
        <div id="background" class="img1"></div>
    </body>
</html>

的javascript:

$(document).ready(function() {

    var $fader = $("#fader");
    var $bg = $("#background");
    var cur_img = 0;
    var img_num = 5;

    setInterval(function () {
        var next_img = (cur_img === img_num - 1) ? 0 : cur_img + 1;
        $fader.removeClass().addClass("img" + cur_img.toString()).css("display", "block").fadeOut(2000);
        $bg.removeClass().addClass("img" + next_img.toString());
        cur_img = next_img;
    }, 5000);
});

CSS

.img1 { background-color: red; }
.img2 { background-color: green; }
.img3 { background-color: blue; }
.img4 { background-color: yellow; }
.img5 { background-color: grey; }

.bg_div {
    position: absolute;
    width: 100%;
    height: 100%;
}

#background { 
    z-index: 1; 
    position: absolute;
    width: 100%;
    height: 100%;
}
#fader { 
    z-index: 2;
    position: absolute;
    width: 100%;
    height: 100%;
}