Using jQuery.queue with multiple element animations?

早过忘川 提交于 2019-11-28 22:09:32

You have a lot of options, but here is what I would do (because I like the self-explanatory syntax):

$.when(
    $("#header").animate({opacity: 1}, 3000).promise(),
    $("#header").animate({top: 0}, 3000).promise()
).done(function() {
    $("#loader").animate({opacity: 0}, 3000).promise()
    .done(function() {
        $("#background").animate({"background-position" : "300px center"}, 3000)
    })
})

Demo: http://jsfiddle.net/vjazX/

You have a few options.

Delay it:

$("#loader").delay(6000).animate({"opacity":"0"},{duration:3000});
$("#background").delay(9000).animate({"background-position" : "300px center"},{duration:3000});

Use callbacks:

function startupAnime() {

    $("#header").animate({"opacity":"1"},3000);
    $("#header").animate({"top":"0px"},3000,function(){
        $("#loader").animate({"opacity":"0"},3000,function(){
            $("#background").animate({"background-position" : "300px center"},3000);
        });
    });   

}

or use deferred objects:

function startupAnime() {

    $("#header").animate({"opacity":"1"},3000);
    $("#header").animate({"top":"0px"},3000).promise().done(function(){
        $("#loader").animate({"opacity":"0"},3000).promise().done(function(){
            $("#background").animate({"background-position" : "300px center"},3000);
        });
    });   

}

Another deferred object option:

function startupAnime() {

    $("#header").animate({"opacity":"1"},3000);
    $("#header").animate({"top":"0px"},3000).promise().then(function(){
        return $("#loader").animate({"opacity":"0"},3000).promise();
    }).done(function(){
        $("#background").animate({"background-position" : "300px center"},3000);
    });

}  

I won't even post the custom queueing because that just gets ridiculous.

None of them are really very clean. Pick your poison. The .delay() looks the cleanest to me, but may be less maintainable. Though the alternatives aren't that maintainable either.

If i had to, I would use the 2nd deferred object sample because i don't feel comfortable with the delay and hate the pyramid of doom.

Try using jQuery promise API. You can pull the promise from each jQuery element and then attach a done callback to it.

For example,

$("#header").animate({"opacity":"1"},{duration:3000 }).promise().done(function () {
    $("#header").animate({ "top":"0px" },{ duration:3000 });
});

You can refer to jQuery's promise API for more information. http://api.jquery.com/promise/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!