Can jquery animations be chained programmatically?

邮差的信 提交于 2019-12-20 04:25:23

问题


I have this code:

jQuery('#flash').animate({opacity: 0.35}, 200)
                .animate({opacity: 0}, 200)
                .animate({opacity: 0.35}, 200)
                .animate({opacity: 0}, 200)
                .animate({opacity: 0.35}, 200)
                .animate({opacity: 0}, 600)

and I'm not decided on how many times I want its state altered. Is there a way to chain animations programmatically instead having to add/remove chain elements by editing the animate chain?


回答1:


No, you can't chain animations without editing the animation queue. If you want to chain a variable, but limited number of times you can do easily with a loop:

var flash = $("#flash");
for (var i=0; i<n; i++)
    flash.animate({opacity: 0.35}, 200).animate({opacity: 0}, 200);

If you want an endless loop, or one that stops when a condition is to be fulfilled in the future, you want to hook a callback on the animation queue, restarting the function:

var flash = $("#flash");
function anim() {
    // if (condition)
    flash.animate({opacity: 0.35}, 200).animate({opacity: 0}, 200, anim);
                                            // call "recursively": ^^^^
}
anim();



回答2:


If I understand correctly you only need a FOR loop:

function animate_n_times(n) {
   var flash = $('#flash');
   for(var i=0;i<n;i++) {
      flash.animate({opacity: 0.35}, 200)
           .animate({opacity: 0}, 200);
   }

}

then called like:

animate_n_times(3);



回答3:


You can chain the animation using a loop if that's what you're looking for.

var $flash = jQuery('#flash'), i;

for (i = 0; i < 10; i++) {
    $flash = $flash.animate({opacity: 0.35}, 200)
                   .animate({opacity: 0}, 200);
}



回答4:


There is a shorter alternative, using the extension jquery-timing:

Animate a given number of times:

$('#flash').repeat().animate({opacity:0.35}, 200)
    .animate({opacity:0}, 200).until(10);

As endless loop:

$('#flash').repeat().animate({opacity:0.35},200).animate({opacity:0},200,$);

For details see the API of .repeat(), .until(count), and .animate(…,$).



来源:https://stackoverflow.com/questions/12436701/can-jquery-animations-be-chained-programmatically

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