如何解决如何在下一个开始之前等待一个jquery动画完成?
| 我有以下jQuery:$(\"#div1\").animate({ width: \'160\' },200).animate({ width: \'toggle\' },300 );
$(\"#div2\").animate({ width: \'toggle\' },300).animate({ width: \'150\' },200);
我的问题是两者同时发生。我希望div2动画在第一个完成时开始播放。我已经尝试过下面的方法,但是它做同样的事情:
$(\"#div1\").animate({ width: \'160\' },300,ShowDiv() );
....
function ShowDiv(){
$(\"#div2\").animate({ width: \'toggle\' },200);
}
如何让它等待第一个完成?
解决方法
http://api.jquery.com/animate/
动画具有“完成”功能。您应该将第二个动画放置在第一个动画的完整功能中。
编辑:示例http://jsfiddle.net/xgJns/
$(\"#div1\").animate({opacity:.1},1000,function(){
$(\"#div2\").animate({opacity:.1},1000);
});
,$(function(){
$(\"#div1\").animate({ width: \'200\' },2000).animate({ width: \'toggle\' },3000,function(){
$(\"#div2\").animate({ width: \'toggle\' },3000).animate({ width: \'150\' },2000);
});
});
http://jsfiddle.net/joaquinrivero/TWA24/2/embedded/result/
,您可以将函数作为参数传递给动画完成后调用的“ 4”函数。像这样:
$(\'#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);
,按照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);
});
,$(\"#div1\").animate({ width: \'160\' },function () {
$(\"#div2\").animate({ width: \'toggle\' },200); });
这对我有用。我不确定您的原始代码为何无效。也许需要将其装入匿名函数中?