How do I animate in jQuery without stacking callba

2019-01-16 20:30发布

Let's say I have three divs, and I'd like each to animate once the previous one is done. Currently, I write this:

$('div1').fadeOut('slow', function() {
    $('div2').fadeOut('slow', function() {
        $('div3').fadeOut('slow');
    });
});

Which is ugly, but manageable.

Now imagine I have 10 different animations that need to happen one after the other on different elements. Suddenly the code gets so clunky that it's extremely hard to manage...

Here's pseudocode for what I'm looking to do:

$('div1').fadeOut('slow' { delay_next_function_until_done: true } );
$('div2').fadeOut('slow' { delay_next_function_until_done: true } );
$('div3').animate({ top: 500 }, 1000 );

How do I achieve this?

7条回答
欢心
2楼-- · 2019-01-16 21:29

I do that, with this method you can put all divs as you want, only adding or deleting elements in the list var, also you can reorder them and you don't have to worry about the delay time.

var list = [ '#div1', '#div2', '...' ];
var i = 0;
function fade(cb) {
    if (i < list.length) {
        $(list[i]).fadeOut('slow', function() {
            i++;
            fade(cb);
        });
    } else {
        cb && cb();
    }
}
fade();

you can also add a callback when the process ends

fade(function(){alert('end')});

Demo

查看更多
登录 后发表回答