Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

Chaining jQuery animations that affect different elements

$(document).ready(function() {
    $("#div1").fadeIn("slow");
    $("#div2").delay(500).fadeIn("slow");
    $("#div3").delay(2000).fadeIn("slow");
    $("#div4").delay(8000).fadeIn("slow");
});

This is my current setup but I feel like this isn't the best way to write this. I can't find any examples on how you would write this better for timing. Any help? I'd appreciate it.

I should also add that the timing of each element isn't consistent.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...