Change the body background image with fade effect in jquery

后端 未结 7 1620
说谎
说谎 2020-12-01 09:40

Hey i want to fade in a new background image let´s say every 60 seconds. I´ve set the background image like this:

body {background-image: url(background.jpg)         


        
相关标签:
7条回答
  • 2020-12-01 10:27

    Building on the answer from Dan-Nolan (formerly user506980), you can also assign the backgrounds to an array and then call each background from the array with a counter

    jsFiddle Demo

    Further, you can assign the setInterval function to a variable, and then use that variable later to stop the repeats.

    $(document).ready(function() {
        var cnt=0, bg;
        var $body = $('body');
        var arr = ['bg1.jpg','bg2.jpg','bg3.jpg','bg4.jpg','bg5.jpg','bg6.jpg'];
    
        var bgrotater = setInterval(function() {
            if (cnt==5) cnt=0;
            bg = 'url("' + arr[cnt] + '")';
            cnt++;
            $body.css('background-image', bg);
        }, 1000);
    
        //To stop the backgrounds from rotating. Note the critical step above
        //of assigning the setInterval function to a variable, in order to
        //use it again (below) to stop the repeating function
        $('#some_button_id').click(function() {
            clearInterval(bgrotater);
        });
    
    }); //END document.ready
    

    Since I built upon Dan-Nolan's answer, please upvote his answer if you upvote this one. And I see that Deryck has added his, and it is also correct. Upvote.

    0 讨论(0)
提交回复
热议问题