Change Background Color CSS with Timer JQuery

人盡茶涼 提交于 2019-11-28 11:41:09

I dont know if you mean animated as in fading to the next, but heres a simple quick example of changing the color every 2 seconds. First example does not require jQuery.

Live Demo

function changeColor(curNumber){
    curNumber++;

    if(curNumber > 4){
        curNumber = 1;
    }
    document.body.setAttribute('class', 'color' + curNumber);
    setTimeout(function(){changeColor(curNumber)}, 2000);  
}

changeColor(0);

Update animating color

Second example requires Jquery UI if you wish to fade between classes or background colors.

Demo 2

function changeColor(element, curNumber){
    curNumber++;

    if(curNumber > 4){
        curNumber = 1;
    }

    element.addClass('color' + curNumber, 1000);

    // So previous classes get removed.
    element.attr('class', 'color' + curNumber);

    setTimeout(function(){changeColor(element, curNumber)}, 2000);  
}

changeColor($('#testElement'), 0);

UPDATE

I'm sure there are better ways to do this, but just to show you a simple way of accomplishing this...

http://jsfiddle.net/UnsungHero97/QLPbW/5/


You want to use the window.setInterval() function...

window.setInterval(rotateBG, 1000); // 1000 = 1 second

function rotateBG() {
    // logic to rotate background
}

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!