How to loop a css background image with Jquery every few seconds?

前端 未结 3 492
清酒与你
清酒与你 2020-12-09 21:13

I would like to change a header css background image every few seconds, so its look like a slideshow.

For example first 2 seconds be:

body#home h1#s         


        
3条回答
  •  情书的邮戳
    2020-12-09 21:31

    Now with fade

    Try this:

    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);        
    });
    

提交回复
热议问题