Creating a looping background animation in jquery

2019-05-09 06:58发布

问题:

What I want is:

when the page loads - the background has color red after 10 seconds the bgColor changes to green with a fade in fade out animation... after another 10 seconds it changes to orange....then again to red and so on..

Could someone help

回答1:

Use setinterval with a callback that changes the background:

$("document").ready(function() {
    var colours = [ "blue", "orange", "pink" ];
    var counter = 0;
    function cycleBackground() {
        $("body").animate({ backgroundColor: colours[counter] }, 500 );
        counter++;
        if(counter == colours.length) {
            counter = 0;
        }
    }
    setInterval(cycleBackground, 10000);
});

You will need to use jQuery UI's animate function if you want to smoothly cycle between colors.