我正在尝试在新闻项目滚动之间添加延迟。我知道$ .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>
答案 0 :(得分:0)
为了实现这一点,需要在动画完成时进行递归。请注意,为了演示,延迟时间降至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>
答案 1 :(得分:0)
这是一种相当简单的页面加载延迟和转换方法,而不是每5秒一次。这是我使用的,当它不复杂像时间一致的幻灯片。它正在伪装它,但适用于简单的解决方案。
var duration = 5000;
$('className').each(function(n) {
$(this).delay(n * duration).fadeIn().delay(duration).fadeOut();
});