Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

background Image change using jquery

I am changing my background image from this code

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

    jQuery('#absolute-c').css('background-image', function() {
        if (i >= images.length) {
            i=0;
        }
        return 'url(' + images[i++] + ')';      
    });
}, 3000);
})

how do .animate and load first background without delay. due to setInterval my first background also show after 3 sec

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...