【问题标题】:Iterating over child elements one at a time一次迭代一个子元素
【发布时间】:2011-08-15 13:18:29
【问题描述】:

正如标题所述,我正在尝试迭代一组子元素,当我尝试一次将它们淡出一个时,麻烦就来了,我正在使用$.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>

另外,是否可以在当前动画完成之前触发动画,但将其延迟设定的时间间隔?

提前致谢!

【问题讨论】:

    标签: jquery html jquery-animate


    【解决方案1】:

    这里有一个稍微不同的方法:

    创建一个包含所有子元素的数组,而不是使用 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 上查看工作演示。

    希望这会有所帮助!

    【讨论】:

    • @user270311:很高兴能帮上忙! :)
    【解决方案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.
    

    【讨论】:

      【解决方案3】:

      为每个后续渐变添加一个递增的delay

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

      您可能需要调整延迟增量以满足您的需要。

      【讨论】:

        【解决方案4】:

        我认为您会想要使用 $.queue 之类的东西,这样您就不必自己手动确定所有动画的持续时间和计时。 jQuery 的 $.queue 文档链接到 Stack Overflow 上的 this question,它应该为您指明正确的方向。

        【讨论】:

          【解决方案5】:

          为您的 DIV 自己的 ID 提供,然后您可以遍历 ID 并一次淡出一个。 例如:

          var children = $("container").children().each(function() {

          for(var k=0;k $(this).attr('id',$(this).attr('id')); }

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

          【讨论】:

            猜你喜欢
            • 2015-07-26
            • 1970-01-01
            • 2022-08-23
            • 2014-03-12
            • 1970-01-01
            • 1970-01-01
            • 2020-12-05
            • 1970-01-01
            • 2017-11-29
            相关资源
            最近更新 更多