background Image change using jquery

前端 未结 1 709
太阳男子
太阳男子 2020-12-17 08:12

I am changing my background image from this code

jQuery(window).load(function(){
var images = [\'blaa.jpg\',\'sdsd.jpg\'];
var i = 0;
setInterval(function(){         


        
相关标签:
1条回答
  • 2020-12-17 08:39

    You can do create a function for this and use it in the setInterval:

    jQuery(window).load(function(){
        var images = ['blaa.jpg','sdsd.jpg'];
        var i = 0;
    
        function changeBackground() {
            jQuery('#absolute-c').css('background-image', function() {
                if (i >= images.length) {
                    i=0;
                }
                return 'url(' + images[i++] + ')';      
            });
        }
        // Call it on the first time
        changeBackground();
        // Set an interval to continue
        setInterval(changeBackground, 3000);
    });
    

    Another solution, and I think is much better, is to use setTimeout instead:

    jQuery(window).load(function(){
        var images = ['blaa.jpg','sdsd.jpg'];
        var i = 0;
        var timeoutVar;
    
        function changeBackground() {
            clearTimeout(timeoutVar); // just to be sure it will run only once at a time
    
            jQuery('#absolute-c').css('background-image', function() {
                if (i >= images.length) {
                    i=0;
                }
                return 'url(' + images[i++] + ')';      
            });
    
            // call the setTimeout every time to repeat the function
            timeoutVar = setTimeout(changeBackground, 3000);
        }
    
        // Call it on the first time and it will repeat
        changeBackground();        
    });
    
    0 讨论(0)
提交回复
热议问题