Change Background Color CSS with Timer JQuery
I was hoping someone could sh开发者_如何学JAVAow 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
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.
精彩评论