问题
I have a div at the top of a page that I would like to fade in and out 3 times. I found a question/answer already that shows how to fade with an infinite loop by putting the fade effects in a function that calls itself, but I was wondering what the best way to specify a finite number of fade cycles. So far, this is what I have (stolen from another StackOverflow post):
function fade() {
$("#notification").animate({opacity: 1.0}, {duration: 500})
.animate({opacity: 0}, {duration: 500})
.animate({opacity: 0}, {duration: 500})
.animate({opacity: 1.0}, {duration: 500, complete: fade})
}
Apologies in advance for being such a js noob.
回答1:
If you are using the latest version of jQuery (1.4 as of this writing), you can specify such a short cycle with straight function calls:
$("#notification").fadeIn(500).fadeOut(500).delay(500)
.fadeIn(500).fadeOut(500).delay(500)
.fadeIn(500).fadeOut(500);
delay was introduced in jQuery 1.4.
If the repetition bothers you, you could make it a plugin:
$.fn.pulsate = function( number, time){
for(var i = 0; i < number; i++){
this.fadeIn(time).fadeOut(time);
if(i != number - 1) this.delay(time);
}
return this;
}
It could then be used like this:
$("#notification").pulsate( 3, 500 );
回答2:
I think it would be better to use it in callback. Create recursive function with limit of fading.
animation(max, total) {
if (total < max) $(...).animate(..., animation(max, total + 1));
}
来源:https://stackoverflow.com/questions/2094621/jquery-fade-div-in-and-out-multiple-times