jQuery: fade div in and out multiple times

别说谁变了你拦得住时间么 提交于 2020-01-04 21:37:55

问题


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

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