2011-04-29 114 views
3

作爲標題狀態,我試圖迭代子元素的集合,麻煩進來時,當我嘗試逐個淡出它們時,我正在使用$.each()嘗試並實現這一點,但它似乎一下子消失了一切,我希望它做的是等待動畫完成,然後轉到下一個子元素並淡出,這是我的代碼,一次一個地迭代子元素

jQuery的:

var children = $("container").children(); 

children.each(function(){ 
    $(this).fadeOut('slow'); 
}) 

HTML:

<div id="container"> 
    <div style="background: #F00;"></div> 
    <div style="background: #00F;"></div> 
    <div style="background: #0F0;"></div> 
</div> 

另外,是否有可能在當前動畫完成之前觸發動畫,但是將其延遲一段設定的時間間隔?

在此先感謝!

回答

14

這裏有一個稍微不同的方法:

創建所有的子元素的數組,而不是它使用了jQuery對象您最初的代碼。

var children = []; 
$("#container").children().each(function() { 
    children.push(this); 
}); 

創建同時彈出一個元件陣列的功能和動畫它,遞歸調用本身作爲一個回調函數,所以它只有在一個動畫結束後執行。

function fadeThemOut(children) { 
    if (children.length > 0) { 
     var currentChild = children.shift(); 
     $(currentChild).fadeOut("slow", function() { 
      fadeThemOut(children); 
     }); 
    } 
} 

查看關於jsFiddle的工作演示。

希望這會有所幫助!

+0

Thanx,這個伎倆! – Odyss3us 2011-05-05 12:01:04

+0

@ user270311:很高興能有所幫助! :) – 2011-05-05 12:50:23

1

添加,其後每褪色越來越delay

var children = $("container").children(); 

var delayInterval = 0; 
children.each(function(){ 
    if (delayInterval > 0) $(this).delay(delayInterval); 
    $(this).fadeOut('slow'); 
    delayInterval += 300; 
}) 

你可能需要調整延遲增量,以適應​​您的需求。

2

你想在上一次完成褪色後逐一淡化嗎?

See this example on jsFiddle

el.fadeOut("slow", function() { 
    // Fade next (see example) 
}); 

Reference for fadeOut

.fadeOut([ duration ], [ callback ]) 
- duration: A string or number determining how long the animation will run. 
- callback: A function to call once the animation is complete. 
1

我想你會想使用類似$.queue這樣你就不用手動想出的持續時間和定時你的所有動畫自己。 jQuery的$.queue文檔鏈接到this question Stack Overflow應該指向正確的方向。

0

Giv爲你的DIV自己的ID,並且你可以一次一個地讀取ID和褪色。 。 例如:

變種兒童= $( 「容器」)的兒童()每個(函數() {

爲(VAR K = 0; k < $(本).attr(」 ID')。長度; k ++) {
$(this).attr('id',$(this).attr('id')); }

$(this).attr('id')。fadeOut('slow'); });