jquery animate multiple elements with delay

依然范特西╮ 提交于 2019-12-23 04:21:48

问题


I want to animate multiple elements with jQuery one after another, so

$("div").each(function(i){
    $(this).delay(i*1000).animate({left: "+=200"}, {duration: 3000});
});

http://jsfiddle.net/eP2C3/1/
And now I need them to fadeOut while moving. If duration is 3000ms I add 2500ms delay and fade it out in 500ms.

$("div").each(function(i){
    $(this).animate({left: "+=200"}, {duration: 3000, queue: false})
            .delay(2500)
            .animate({opacity: 0}, {duration: 500});
});

http://jsfiddle.net/eP2C3/
But if I combine it with previous example they would animate simultaneously. And delay only opacity animation.

$("div").each(function(i){
    $(this).delay(i*1000).animate({left: "+=200"}, {duration: 3000, queue: false})
            .delay(2500)
            .animate({opacity: 0}, {duration: 500});
});

http://jsfiddle.net/eP2C3/2/


回答1:


You should remove the queue: false. The delay() will be ignored if you specify the animation not to be queued because delay is a callback that is also added to the queue.

Here I've updated your jsfiddle: http://jsfiddle.net/eP2C3/10/


Update:

If you need opacity animation to start after 2500ms from the start left animation then queue: false should be applied to do this. However .delay(i*1000) will be ignored but a good workaround is to use setTimeout() to begin the animation:

$("div").each(function(i){
    var div = $(this);
    setTimeout(function(){
    div.animate({left: "+=200"}, {duration: 3000, queue: false})
            .delay(2500).animate({opacity: 0}, {duration: 500});
    },i*1000);
});

See this updated jsfiddle: http://jsfiddle.net/eP2C3/36/




回答2:


Ok, the problem was slightly more complicated than I thought, but I think i have an answer now. Unfortunately you cannot use jQuery animate function, because it is queueing your animations and you cannot apply two animations with different settings at the same time (at least to my knowledge). So you can try something like this:

$('div').each(function (i) {
    var $this = $(this);
    $this.delay(i * 1000).animate(
        {
            left: '+=200'
        },
        {
            duration: 3000,
            start: function () {
                setTimeout(function () {
                    setInterval(function () {
                        $this.css({opacity: '-=0.04'});
                    }, 30);
                }, 2500);
            }
        }
    );
});

The setInterval function is used to create the animation effect. I hope this helps. JSFiddle here: http://jsfiddle.net/eP2C3/44/



来源:https://stackoverflow.com/questions/21572326/jquery-animate-multiple-elements-with-delay

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