等待循环中的每个动画在 运行 下一个之前完成
Waiting for each animation in loop to finish before running the next one
我正在寻找 运行 计数功能的延迟,因此每当完成 class 计数器名称完成时,它就会 运行 每当前一个一个已经完成等等
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 4000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
这不适用于 each
循环。您必须使用 complete
回调并自行执行,因为动画是异步的。
我会使用递归的自执行函数。很简单,完成后开始下一个。
var elements = $('.counter');
var current = 0;
(function next() {
var $this = elements.eq(current),
countTo = $this.attr('data-count');
$({countNum: $this.text()}).animate({countNum: countTo}, {
duration: 4000,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
if( (++current) < elements.length ) {
next();
}
}
});
})();
我正在寻找 运行 计数功能的延迟,因此每当完成 class 计数器名称完成时,它就会 运行 每当前一个一个已经完成等等
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({ countNum: $this.text()}).animate({
countNum: countTo
},
{
duration: 4000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
这不适用于 each
循环。您必须使用 complete
回调并自行执行,因为动画是异步的。
我会使用递归的自执行函数。很简单,完成后开始下一个。
var elements = $('.counter');
var current = 0;
(function next() {
var $this = elements.eq(current),
countTo = $this.attr('data-count');
$({countNum: $this.text()}).animate({countNum: countTo}, {
duration: 4000,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
if( (++current) < elements.length ) {
next();
}
}
});
})();