【问题标题】:Infinite animation opacity not works for several elements无限动画不透明度不适用于多个元素
【发布时间】:2019-03-10 09:35:13
【问题描述】:

HTML:

<div id="my_div" class="all_divs"></div>
<div class="all_divs"></div>
<div class="all_divs"></div>

CSS:

.all_divs {
   width: 100px;
   height: 100px;
   background: #009;
   margin-top: 10px;
   opacity: 0;
}

JS/JQUERY:

function light() {
    $("#my_div").animate({opacity: 1}, 500, function() {
        shutdown();
    });
}

function shutdown() {
    $("#my_div").animate({opacity: 0}, 500, function() {
        light();
    });
}

$(document).ready(function() {
    light();
});

当我尝试只为一个 div (id="my_div") 设置动画时,这可以正常工作,但是当尝试使用 $(".all_divs") 为所有 3 个元素设置动画时,动画会崩溃。

这是什么原因?

Here is an example, when the selector is class .all_divs and animation crashes:

https://jsfiddle.net/oL65jax0/

这是预期的结果:

https://jsfiddle.net/oL65jax0/1/

【问题讨论】:

    标签: javascript jquery jquery-animate


    【解决方案1】:

    发生这种情况是因为您的“动画结束”回调为每个具有 all_divs 类的元素调用 light()shutdown()(每次 3 次)。解决此问题的一种方法是仅对最后一个元素调用 light()shutdown()

        function light() {
            $(".all_divs").animate({opacity: 1}, 500, function(i) {
              if (this === $(".all_divs").last().get(0))
                shutdown();
            });
        }
        function shutdown() {
            $(".all_divs").animate({opacity: 0}, 500, function() {
              if (this === $(".all_divs").last().get(0))
                light();
            });
        }
    
    
        $(document).ready(function() {
            light();
        });
    .all_divs {
      width: 100px;
      height: 100px;
      background: #009;
      margin-top: 10px;
      opacity: 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="my_div" class="all_divs"  ></div>
    <div class="all_divs"  ></div>
    <div class="all_divs" ></div>

    或者您可以将最后一个元素保存在某处,这样您就不必重新计算它。

    function light() {
        $(".all_divs").animate({opacity: 1}, 500, function(i) {
          if (this === App.lastAnimatedElement)
            shutdown();
        });
    }
    function shutdown() {
        $(".all_divs").animate({opacity: 0}, 500, function() {
          if (this === App.lastAnimatedElement)
            light();
        });
    }
    
    var App = App || {};
    
    $(document).ready(function() {
      App.lastAnimatedElement = $(".all_divs").last().get(0);
      light();
    });
    .all_divs {
      width: 100px;
      height: 100px;
      background: #009;
      margin-top: 10px;
      opacity: 0;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="my_div" class="all_divs"  ></div>
    <div class="all_divs"  ></div>
    <div class="all_divs" ></div>

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 2012-01-20
      • 2017-05-05
      • 2010-09-25
      • 2018-02-15
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多