Javascript 如何在下一个jquery动画开始之前等待一个jquery动画完成?

Javascript 如何在下一个jquery动画开始之前等待一个jquery动画完成?,javascript,jquery,animation,callback,sequential,Javascript,Jquery,Animation,Callback,Sequential,我有以下jQuery: $("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300 ); $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); 我的问题是两者同时发生。我想div2动画开始时,第一个完成。我尝试了下面的方法,但效果相同: $("#div1").animate({ width: '160' }

我有以下jQuery:

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300 );
$("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200);
我的问题是两者同时发生。我想div2动画开始时,第一个完成。我尝试了下面的方法,但效果相同:

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, ShowDiv() );
....
function ShowDiv(){
   $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200);
}
如何让它等待第一个完成?

动画具有“完整”功能。您应该将第二个动画放置在第一个动画的完整功能中

编辑:示例


可以将函数作为参数传递给动画完成后调用的函数。像这样:

$('#div1').animate({
    width: 160
}, 200, function() {
    // Handle completion of this animation
});
下面的示例更清楚地解释了这些参数

var options = { },
    duration = 200,
    handler = function() {
        alert('Done animating');
    };

$('#id-of-element').animate(options, duration, handler);

不要使用超时,使用完整的回调

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, function(){

  $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200);

});
$(function(){
    $("#div1").animate({ width: '200' }, 2000).animate({ width: 'toggle' }, 3000, function(){
    $("#div2").animate({ width: 'toggle' }, 3000).animate({ width: '150' }, 2000);
    });
});

按照kingjiv所说的,您应该使用
complete
回调来链接这些动画。在第二个示例中,您几乎看到了它,除了在它后面加括号立即执行ShowDiv回调之外。将其设置为
ShowDiv
而不是
ShowDiv()
,它应该可以工作

mcgrailm的回复(在我写这篇文章时发布)实际上是一样的,只是对回调使用了匿名函数

$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, function(){

  $("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200);

});
$(function(){
    $("#div1").animate({ width: '200' }, 2000).animate({ width: 'toggle' }, 3000, function(){
    $("#div2").animate({ width: 'toggle' }, 3000).animate({ width: '150' }, 2000);
    });
});


这对我有用。我不知道你的原始代码为什么不起作用。也许它需要包含在匿名函数中

这不是我在第二个例子中所做的吗?你的第二个例子实际上很接近。从第一行的
ShowDiv
中删除
()
。您正在调用函数而不是传递它。嘎!谢谢如果需要,我如何传递参数?只需删除
()
,函数就可以像任何其他变量一样传递,只需不添加
()
,它将调用函数并传递返回值。哦,是的,您只需将其包装在函数中,这样
函数(){ShowDiv('something')}
将是animage的第三个参数。