2011-04-28 102 views
8

我試圖同時動畫一組元素(差不多了,還有每個動畫之間有一個小的延遲):jQuery的多個動畫()回調

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

如何運行一個回調函數後,所有動畫都完成?

+0

您可以將各個單獨動畫。增加一個值,如果該值是=動畫數量,那麼運行實際功能 – davidosomething 2011-04-28 18:43:03

+1

是否有一個原因,在整個$(「。block」)。each語句之後不能調用mycallbackfunction?還是我誤解你的代碼? – 2011-04-28 18:44:12

+0

是的。如果我這樣做,該功能將立即執行。我想等待動畫完成,然後執行它 – Alex 2011-04-28 18:45:32

回答

5

圍繞計數器變量使用閉包。

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

請注意,將項目列表保存到$ block變量中以保存查找。

+0

只是在'myCallbackFn()'中進行遞減......但是這是我看到的唯一答案 – 2011-04-28 18:51:51

+0

爲了在mycallbackfunction()中執行遞減操作,它需要在與'count'相同的範圍內定義。 OP的例子沒有顯示mycallbackfunction()是在哪裏定義的。 – kcbanner 2011-04-28 18:53:33

+0

謝謝!這似乎工作:D,但你有一個錯誤:它應該是'if(count == 0)mycallbackfunction();' – Alex 2011-04-28 18:57:28

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

因爲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

+0

即使通過'.stop()'停止動畫,也會觸發回調。 – antitoxic 2011-09-29 17:58:30