如何使用Jquery每隔几秒循环一次css背景图像?

时间:2009-09-03 17:39:34

标签: jquery css

我想每隔几秒更改一次标题css背景图片,所以它看起来像幻灯片。

例如前2秒:

body#home h1#siteH1 { background:url(../images/header1.jpg) no-repeat;}

接下来2秒:

body#home h1#siteH1 { background:url(../images/header2.jpg) no-repeat;}

接下来2秒:

body#home h1#siteH1 { background:url(../images/header3.jpg) no-repeat;}

然后再循环到header1。

如果有人知道如何通过淡化效果进行过渡,那么它将是完美的。

3 个答案:

答案 0 :(得分:19)

现在退色

试试这个:

var currentBackground = 0;
var backgrounds = [];
backgrounds[0] = '../images/header1.jpg';
backgrounds[1] = '../images/header2.jpg';
backgrounds[2] = '../images/header3.jpg';

function changeBackground() {
    currentBackground++;
    if(currentBackground > 2) currentBackground = 0;

    $('body#home h1#siteH1').fadeOut(100,function() {
        $('body#home h1#siteH1').css({
            'background-image' : "url('" + backgrounds[currentBackground] + "')"
        });
        $('body#home h1#siteH1').fadeIn(100);
    });


    setTimeout(changeBackground, 2000);
}

$(document).ready(function() {
    setTimeout(changeBackground, 2000);        
});

答案 1 :(得分:3)

签出队列功能:

jQuery Queue

答案 2 :(得分:1)

晚会,但这是我刚才提出的类似要求。

 <script type="text/javascript">
 //populate image set
 var imageAry = ["1.jpg","2.jpg","3.jpg","4.jpg"];
 //in milliseconds
 var fadeSpeed = "1000";
 var timeout = 3000;


function fadeInFront (i){
    $('#faderFront').css( {
        "background-image" : "url("+imageAry[i]+")"
    });
    $('#faderFront').fadeIn(fadeSpeed);
    i++;
    if (i==imageAry.length){i=0;}
    setTimeout(function(){
        fadeOutFront(i);
    },timeout);
}
function fadeOutFront (i){
    $('#faderBack').css( {
        "background-image" : "url("+imageAry[i]+")"
    });
    $('#faderFront').fadeOut(fadeSpeed);
    i++;
    if (i==imageAry.length){i=0;}
    setTimeout(function(){
        fadeInFront(i);
    },timeout);
}
 function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
    });
}

$(document).ready(function(){
    preload(imageAry);
    setTimeout(function(){
        fadeOutFront(3);
    },timeout);
});
</script>

 <style type="text/css">

            #faderBack,
            #faderFront,
            #inFrontOfBoth
            {
                position: absolute;
                top: 0;
                left: 0;
            }
            #faderFront
            {
                background: url("4.jpg") no-repeat center top;
            }
 </style>

 <body>

 <div id="container">

    <div id="faderBack"></div>
    <div id="faderFront"></div>
    <div id="inFrontOfBoth">Hello World</div>
</div>