12

我有以下 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);
}

我怎样才能让它等待第一个完成?

4

6 回答 6

21

http://api.jquery.com/animate/

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

编辑:示例http://jsfiddle.net/xgJns/

$("#div1").animate({opacity:.1},1000,function(){
    $("#div2").animate({opacity:.1},1000);    
});​
于 2011-05-24T20:44:05.357 回答
2
$(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/

于 2011-05-24T20:55:48.017 回答
1

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

$('#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);
于 2011-05-24T20:44:57.840 回答
1

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

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

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

});
于 2011-05-24T20:50:58.220 回答
1

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

mcgralm 的响应(在我写这篇文章时发布)实际上是相同的,只是使用匿名函数进行回调。

于 2011-05-24T20:51:09.310 回答
0
$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, function () {
$("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); });

这对我有用。我不确定为什么您的原始代码不起作用。也许它需要被装入匿名函数中?

于 2011-05-24T20:56:06.517 回答