简体   繁体   English

jQuery 多个 animate() 回调

[英]jQuery multiple animate() callback

I'm trying to animate a set of elements simultaneously (almost, there's a small delay between each animation):我正在尝试同时为一组元素设置动画(几乎每个动画之间都有一点延迟):

$('.block').each(function(i){
   $(this).stop().delay(60 * i).animate({
     'opacity': 1
   }, {
      duration: 250,
      complete: mycallbackfunction // <- this fires the callback on each animation :(
   });
});

How can I run a callback function after all animations have completed?在所有动画完成后,如何运行回调 function?

Use a closure around a counter variable.在计数器变量周围使用闭包。

var $blocks = $('.block');
var count = $blocks.length;
$blocks.each(function(i){
   $(this).stop().delay(60 * i).animate({
     'opacity': 1
   }, {
      duration: 250,
      complete: function() {
        if (--count == 0) {
          // All animations are done here!
          mycallbackfunction();
        }
      }
   });
});

Note the saving of the list of items into the $block variable to save a lookup.请注意将项目列表保存到 $block 变量中以保存查找。

Since jQuery 1.5, you can use $.when [docs] , which is a bit easier to write and understand:由于 jQuery 1.5,您可以使用$.when [docs] ,这更容易编写和理解:

var $blocks = $('.block');

$blocks.each(function(i){
   $(this).stop().delay(60 * i).animate({
     'opacity': 1
   }, {
      duration: 250
   });
});

$.when($blocks).then(mycallbackfunction);

DEMO演示

Felix Kling's answer will fire the callback when there's no animation left to do.当没有 animation 要做时, Felix Kling 的回答将触发回调。 This makes the callback firing even if the animation is stopped via $el.stop() and thus not completed to the end.即使animation 通过$el.stop()停止并且因此未完成到最后,这也会触发回调。

I found an method by Elf Sternberg using deferred objects which I implemented in this jsfiddle:我找到了Elf Sternberg 使用我在这个 jsfiddle 中实现的延迟对象的方法

http://jsfiddle.net/8v6nZ/ http://jsfiddle.net/8v6nZ/

   var block = $('.block');
   block.each(function(i){
   $(this).stop().delay(60 * i).animate({
     'opacity': 1
    }, {
      duration: 250,
      complete: i== (block.length-1) ? myCallbackFunction : function(){}
    });
   });
$('.block').each(function(i){
   $(this).stop().delay(60 * i).animate({
     'opacity': 1
   }, {
      duration: 250,
      complete: ((i == $('.block').length - 1) ? mycallbackfunction : null)
   });
});

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

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