首页 > 解决方案 > Jquery 用 each() 链接动画

问题描述

我正在使用列表中的每个项目元素制作动画。我的目标是当每个项目完成动画功能时,下一个项目开始动画等等。现在,我所做的只是所有项目同时运行动画功能。项目列表应该有数百个项目,我只演示了 3 个项目。

$(document).ready(function() {
      $('.list-item').each(function(){
        var _this = $(this);
        _this.find(".loading").animate({
            width: "100%"
        }, 2500);
    });
})
.list-item .item {
  position: relative;
  }
  .list-item .item {
  padding: 20px;
  margin-bottom:10px;
  }
  .list-item .item .loading {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 0;
    background: lightblue;
    opacity: 0.3;
    -webkit-transition: none !important;
    transition: none !important;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
    <div class="item">
        Item 1
        <span class="loading">&nbsp;</span>
    </div>
    <div class="item">
        Item 2
        <span class="loading">&nbsp;</span>
    </div>
    <div class="item">
        Item 3
        <span class="loading">&nbsp;</span>
    </div>
</div>

标签: javascriptjquery

解决方案


您可以使用setTimeout()动态delay来实现

$(document).ready(function() {
  var delay = 0;
  $('.list-item .loading').each(function() {
    var _this = $(this);
    setTimeout(function() {
      _this.animate({
        width: "100%"
      }, 2500);
    }, delay)
    delay += 2500;


  });
})
.list-item .item {
  position: relative;
}

.list-item .item {
  padding: 20px;
  margin-bottom: 10px;
}

.list-item .item .loading {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 0;
  background: lightblue;
  opacity: 0.3;
  -webkit-transition: none !important;
  transition: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-item">
  <div class="item">
    Item 1
    <span class="loading">&nbsp;</span>
  </div>
  <div class="item">
    Item 2
    <span class="loading">&nbsp;</span>
  </div>
  <div class="item">
    Item 3
    <span class="loading">&nbsp;</span>
  </div>
</div>


推荐阅读