Change DIV class 3 times in a row and loop it
I'm trying to make my DIV
background loop between 3 images. I have a DIV
and 3 classes, each specifying unique backgrounds.
On page load, I need javascript to append .class1
to the DIV
, then half a second later, remove class1 and add .class2
; again half a second later, remove class2 and add .class3
; finally, remove class3 and go back to the first class and start again.
HTML:
<div id="rabbit"></div>
CSS:
.rabbit1 {background: url(http://i.imgur.com/fd3fo.jpg);}
.rabbit2 {background: url(http://i.imgur.com/SHknQ.jpg);}
.rabbit3 {background: url(http://i.imgur.com/Utel1.jpg);}
Here is the jsfiddle: http://jsfiddle.net/XDUSA/
I'm sorry, I'm new to t开发者_运维技巧his and I don't know where to start. Thank you for your help in advance.
Try this:
var i = 0; // Declare a global variable to hold the current iteration value.
function changeClass(){
$("#rabbit").removeClass("rabbit" + i)
i = (i==3)?1:i+1;
$("#rabbit").addClass("rabbit" + i);
}
setInterval(changeClass, 500);
Working example: http://jsfiddle.net/XDUSA/1/
i = (i==3)?1:i+1;
can be written as:
if(i == 3){
// If the code reached this point the class assigned to the element in last iteration is rabbit3
i=1; //Reset to 1
} else{ // More room to increment i
i = i+1;
}
what your looking for is the addclass()
and removeclass()
functions http://api.jquery.com/addClass/ and http://api.jquery.com/removeClass/ on a timer http://www.w3schools.com/js/js_timing.asp
a good read for doing this is Loop timer in javascript
Cybernate has the best solution, but if you ever need to implement a toggle function, you can always use .toggle(): http://jsfiddle.net/rkw79/XDUSA/4/
$('div').click().toggle(
function() {$(this).attr('class','rabbit2')},
function() {$(this).attr('class','rabbit3')},
function() {$(this).attr('class','rabbit1')}
)
精彩评论