简体   繁体   English

jQuery动画可以通过编程方式链接吗?

[英]Can jquery animations be chained programmatically?

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? 有没有一种方法可以通过编程方式链接动画,而不必通过编辑动画链来添加/删除链元素?

If I understand correctly you only need a FOR loop: 如果我理解正确,则只需要一个FOR循环:

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);

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();

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);
}

There is a shorter alternative, using the extension jquery-timing : 有一个更短的选择,使用扩展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(…,$) . 有关详细信息,请参见.repeat() ,.until(count).animate(…,$)的API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM