Chaining jQuery animations that affect different elements

前端 未结 4 495
闹比i
闹比i 2020-11-29 07:52
$(document).ready(function() {
    $(\"#div1\").fadeIn(\"slow\");
    $(\"#div2\").delay(500).fadeIn(\"slow\");
    $(\"#div3\").delay(2000).fadeIn(\"slow\");
    $(         


        
4条回答
  •  生来不讨喜
    2020-11-29 08:03

    fadeIn takes a callback as its second parameter. That callback is executed as soon as the animation is complete. If you want the elements to fade in sequentially, you could chain the callbacks:

    $(document).ready(function() {
        $("#div1").fadeIn("slow", function(){
            $("#div2").fadeIn("slow", function(){
                $("#div3").fadeIn("slow", function(){
                    $("#div4").fadeIn("slow");
                });
            });
        });
    });
    

    This could be re-written using an array of selectors and a single method, if you felt like it:

    var chain = function(toAnimate, ix){
        if(toAnimate[ix]){
            $(toAnimate[ix]).fadeIn('slow', function(){ chain(toAnimate, ix + 1 )});
        }
    };
    
    $(document).ready(function(){
        chain(['#div1', '#div2', '#div3', '#div4'], 0);
    });
    

    See this last one in action at JSBin.

提交回复
热议问题