我正在尝试在新闻滚动之间添加延迟。我知道$ .each()的工作方式是不等待动画完成,但是我想知道如何制作它,因此一次向上滚动一个项目,并等到最后一个动画完成后再继续在循环。



$(function() {
  var parentHeight = $("#news_updates").height();
  $(".updateItem").css("top", parentHeight);


  $("#news_updates").children().each(function() {
    scrollr($(this));
  });

  function scrollr(itemToScroll) {
    itemToScroll.animate({top: '40%'}, 3000).delay(7000).animate({top: -35}, 3000);
  }
});

body
{
  background-color: lightgrey;
}
#sponsor_updates {

}
#news_updates
{
  overflow: hidden;
  background-color: black;
  height: 250px;
  width: 300px;
  color: white;
  position: relative;
}
#sponsor_updates h2
{
  color: white;
}
.updateItem
{
    position: absolute;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="sponsor_updates">
	<h2>News & Updates</h2>
	<div id="news_updates">
    <div class="updateItem">
      <p>News Item 1</p>
    </div>
    <div class="updateItem">
      <p>News Item 2</p>
    </div>
    <div class="updateItem">
      <p>News Item 3</p>
    </div>
    </div>
	</div>
</div>
</body>
</html>

最佳答案

为了实现这一点,需要在动画完成时递归。请注意,为了进行此演示,延迟已降至700。



$(function() {
  var parentHeight = $("#news_updates").height();
  $(".updateItem").css("top", parentHeight);


  //collect items for recursion
  var items = $("#news_updates").children();

  //immediately call a named function to recurse with
  //break out when items are no longer present
  (function scrollr(items,index) {
    var itemToScroll = items.eq(index++);
    if(!itemToScroll.length)return;
    itemToScroll.animate({top: '40%'}, 3000).delay(700).animate({top: -35}, 3000,function(){ scrollr(items,index); })
  })(items,0)
});

body
{
  background-color: lightgrey;
}
#sponsor_updates {

}
#news_updates
{
  overflow: hidden;
  background-color: black;
  height: 250px;
  width: 300px;
  color: white;
  position: relative;
}
#sponsor_updates h2
{
  color: white;
}
.updateItem
{
    position: absolute;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<div id="sponsor_updates">
	<h2>News & Updates</h2>
	<div id="news_updates">
    <div class="updateItem">
      <p>News Item 1</p>
    </div>
    <div class="updateItem">
      <p>News Item 2</p>
    </div>
    <div class="updateItem">
      <p>News Item 3</p>
    </div>
    </div>
	</div>
</div>
</body>
</html>

09-26 19:42