How to wait for one jquery animation to finish bef

2019-02-12 15:45发布

I have the following jQuery:

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

My issue is that both happen at the same time. I would like the div2 animation to start when the first one finishes. I've tried the method below, but it does the same thing:

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

How can I make it wait for the first one to finish?

6条回答
何必那么认真
2楼-- · 2019-02-12 16:04

Following what kingjiv said, you should use the complete callback to chain these animations. You almost have it in your second example, except you're executing your ShowDiv callback immediately by following it with parentheses. Set it to ShowDiv instead of ShowDiv() and it should work.

mcgrailm's response (posted as I was writing this) is effectively the same thing, only using an anonymous function for the callback.

查看更多
We Are One
3楼-- · 2019-02-12 16:05

You can pass a function as parameter to the animate(..) function which is called after the animation completes. Like so:

$('#div1').animate({
    width: 160
}, 200, function() {
    // Handle completion of this animation
});

The example below is a clearer explanation of the parameters.

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

$('#id-of-element').animate(options, duration, handler);
查看更多
我只想做你的唯一
4楼-- · 2019-02-12 16:09

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

animate has a "complete" function. You should place the 2nd animation in the complete function of the first.

EDIT: example http://jsfiddle.net/xgJns/

$("#div1").animate({opacity:.1},1000,function(){
    $("#div2").animate({opacity:.1},1000);    
});​
查看更多
一夜七次
5楼-- · 2019-02-12 16:13

Don't use a timeout, use the complete callback.

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

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

});
查看更多
老娘就宠你
6楼-- · 2019-02-12 16:15
$(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/

查看更多
你好瞎i
7楼-- · 2019-02-12 16:16
$("#div1").animate({ width: '160' }, 200).animate({ width: 'toggle' }, 300, function () {
$("#div2").animate({ width: 'toggle' }, 300).animate({ width: '150' }, 200); });

This works for me. I'm not sure why your original code doesn't work. Maybe it needs to be incased in an anonymous function?

查看更多
登录 后发表回答