两个连续的动画将不会在jQuery中运行

Two consecutive Animation will not run in jQuery

本文关键字:jQuery 运行 动画 两个 连续      更新时间:2023-09-26

请看下面的脚本:

<style type="text/css">
    .div1
    {
        background-color: Aqua;
        width: 400px;
        height: 30px;
    }
    .div2
    {
        background-color: Fuchsia;
        width: 400px;
        height: 30px;
    }
    .div3
    {
        background-color: Green;
        width: 400px;
        height: 30px;
    }
    .div4
    {
        background-color: Orange;
        width: 400px;
        height: 30px;
    }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        var timer = setInterval(showDiv, 2000);
        var counter = 0;
        function showDiv() {
            if (counter == 0) { counter++; return; }
            $('div.My').css('height', '30px');
            $('div.My').animate({ height: '30' }, 2000, function () { alert('i'); });
            $('div.My')
                .stop()
                .filter(function () { return this.id.match('div' + counter); })
                .animate({ height: '50' }, 500, function () { });
            counter == 4 ? counter = 0 : counter++;
        }
    });
</script>
<body>
<div>
    <div class="div1 My" id="div1">
    </div>
    <div class="div2 My" id="div2">
    </div>
    <div class="div3 My" id="div3">
    </div>
    <div class="div4 My" id="div4">
    </div>
</div>
</body>

我想每隔5秒我的div变大然后变为normal然后下一个div变大。问题是第一个动画不运行,只有第二个动画运行。问题在哪里?

JSFiddle样本

编辑1)

我想当下一个div变大时,前一个div同时变正常。

检查我的叉子你的小提琴,让我知道这是做什么你想要的。你在中间调用了.stop(),它阻止了缓慢收缩动画的显示。

现在完整的脚本是:
$(document).ready(function () {
  var timer = setInterval(showDiv, 2000);
  var counter = 0;
  function showDiv() {
     if (counter == 0) { counter++; return; }
     $('div.My').animate({ height: '30px' }, { duration: 500, queue: false });
     $('div.My')
      .filter(function () { return this.id.match('div' + counter); })
      .animate({ height: '50px' }, { duration: 500, queue: false });
     counter == 4 ? counter = 0 : counter++;
  }
});

编辑-新建提琴

我觉得上面的代码不对,它在我的浏览器中没有像预期的那样工作,所以我找到了一种不同的方法,我认为它工作得更干净。这个使用jQuery的step选项。我还使用addClassremoveClass作为一种本地存储,以记住哪个div需要在下一个动画中收缩。您可以对counter进行一些计算并得到相同的结果,但这是有效的。

$(document).ready(function () {
    var timer = setInterval(showDiv, 2000);
    var counter = 0;
    function showDiv() {
       if (counter == 0) { counter++; return; }
       $shrinker = $("div.big").removeClass("big");
       $grower = $("#div"+counter);
       $grower
        .animate({ height:50 },
         {duration:500,
          step: function(now, fx) {
           $shrinker.css("height", 80-now);
          }
         }
        );
      $grower.addClass("big");
      counter == 4 ? counter = 0 : counter++;
    }
});

step体看起来有点奇怪,但它保证在动画的每个时刻,div堆栈的总高度保持不变。基本上,收缩和增长div的总高度(min:30, max:50)必须始终为80,因此收缩div的高度应该为80——增长div的高度。