How do I animate in jQuery without stacking callbacks?

后端 未结 7 1555
闹比i
闹比i 2020-12-08 05:37

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()          


        
相关标签:
7条回答
  • 2020-12-08 06:19

    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

    0 讨论(0)
提交回复
热议问题