有没有一种方法可以使我的 span
标签一一动画化,而无需超时或间隔函数?我可以轻松地使用 key 和 ID 来执行此操作,但这似乎不是最好的方法。这是我在 fiddle 示例中的内容
更新
别介意原来的问题,据我所知,您需要使用 delay()
函数。我唯一的问题是,如何在不使用初始动画延迟的情况下立即启动此动画?更新了下面的代码和 fiddle 。
var credits = $('#credits'),
container = credits.parent(),
conPos = container.position(),
creditsText = credits.find('span'),
first = 0;
delay = 1000,
count = creditsText.length;
container.fadeIn('slow', function() {
creditsText.each(function() {
$(this).css({
'top': ( conPos.top - $(this).height() ),
'left': ( ( ( conPos.left + container.width() ) - $(this).width() ) / 2 )
}).delay(delay)
.animate({
'top': ( ( ( conPos.top + container.height() ) - $(this).height() ) / 2 ),
'opacity': '1.0'
},
{
duration: 4000,
complete: function() {
$(this).fadeOut(5000);
}
});
if ( first == 1 ) {
delay = 9000;
}
first++;
delay += delay;
});
});
JSFiddle Example
您会注意到前两个“制作人员名单”几乎同时播放,而不是一次播放一个。然后最后一行需要永远显示,就像在正确的计时器上一样。
最佳答案
你可以使用 promise 来解决这个问题:
var credits = $('#credits'),
container = credits.parent(),
conPos = container.position(),
creditsText = credits.find('span'),
first = 0;
delay = 1000,
count = creditsText.length;
container.fadeIn('slow', function() {
function next() {
var span = $(creditsText.get(first));
if (!span) return;
$.when(
span
.css({
'top': ( conPos.top - span.height() ),
'left': ( ( ( conPos.left + container.width() ) - span.width() ) / 2 )
})
.animate({
'top': ( ( ( conPos.top + container.height() ) - span.height() ) / 2 ),
'opacity': '1.0'
}, { duration: 4000}
)
).then(function(){
return span.fadeOut(5000);
}).then(next);
first++;
}
next();
});
我们正在处理必须连续运行的代码,并且必须等待前一个完成。 Promise 以一种干净利落的方式处理这个问题
关于jquery - 动画延迟,但在页面加载/函数触发时立即启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23188869/