2011-04-29 90 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'); });