Change Background Color CSS with Timer JQuery

断了今生、忘了曾经 提交于 2019-11-27 06:24:22

问题


I was hoping someone could show me efficient JQuery to animate between 4 background colors in a div class.

I would like these events to be triggered by time, not click or hover. I've seen posts on hover and toggle, but as someone not very proficient in JQuery, I didn't feel comfortable copying and pasting parts here and there.

Thank you


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6989584/change-background-color-css-with-timer-jquery

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