jQuery动画延迟回调执行



我尝试从左到右动画3个图像,开始堆叠在彼此的顶部。第三个动画应该立即开始,但它被延迟了。原因是什么?

$('.image').animate({left: '100px'}, 500, function () {
$('.image:eq(1), .image:eq(2)').animate({left: '250px'}, 500, function () {
$('.image:eq(2)').animate({left: '400px'}, 500);
});
});

编辑:我想每个动画只显示一个图像。

https://jsfiddle.net/azeL7mwk/1/

$('.image').animate威胁并动画每个元素,所以你实际上调用第一个回调函数3次,第二个2 * 3次,如果你在第三个动画上放一个回调函数,你会调用它1 * 6次。这不是你想要的行为。

您可以通过执行简单的控制台日志来查看此效果:

$('.image').animate({left: '100px'}, 500, function () {
console.log(1)
$('.image:eq(1), .image:eq(2)').animate({left: '250px'}, 0, function () {
console.log(2)
$('.image:eq(2)').animate({left: '400px'}, 500, function() {
console.log(3)
});
});
});
// OUTPUT:
// 1
// 1
// 1
// 2
// 2
// 2
// 2
// 2
// 2
// 3
// 3
// 3
// 3
// 3
// 3

我建议对第一张图像进行动画,然后立即将第二张图像移动到第一张图像后面并对其进行动画,第三张和第二张图像也是如此。

$('.image:eq(0)').animate({left: '100px'}, 500, function () {  
$('.image:eq(1)').css({left: '100px'}).animate({left: '250px'}, 500, function() {
$('.image:eq(2)').css({left: '250px'}).animate({left: '400px'}, 500);
});
});

你也可以通过分离动画队列来实现这一点,这样更好更简洁:

$('.image:eq(0)')
.animate({left: '100px'}, 500);
$('.image:eq(1)')
.animate({left: '100px'}, 500)
.animate({left: '250px'}, 500);
$('.image:eq(2)')
.animate({left: '100px'}, 500)
.animate({left: '250px'}, 500)
.animate({left: '400px'}, 500);

你也可以延迟动画,但是这种缓动会把事情弄得一团糟

最新更新