Staggering CSS Animations

馋奶兔 提交于 2019-12-19 04:55:27

问题


I have a CSS animation that I want to be applied in 200ms intervals. I've set up the CSS like this:

.discrete {
    position:relative;
    opacity:1;

    -webkit-transition: all .5s linear;
    -moz-transition: all .5s linear;
    -o-transition: all .5s linear;
    transition: all .5s linear;
}

.discrete.out {
    left:-40px;
    opacity:0;    
}

I then want to stagger the application of the .discrete.out class in 200ms intervals. I've tried the following:

$('.discrete').each(function() {
    $(this).delay(200).addClass('out');
});

And this:

$('.discrete').each(function() {
   var theNode = $(this); 
   setTimeout(function() {
       theNode.addClass('out');
    }, 200);
});

But in both cases, the animation just occurs all at once!

Any ideas?


回答1:


You could use

var els = $('.discrete'),
    i = 0,
    f = function () {
        $(els[i++]).addClass('out');
        if(i < els.length) setTimeout(f, 200);
    };
f();

Demo




回答2:


Try using the jQuery animation queue: http://jsfiddle.net/gwwar/7zm6q/2/

function createWorkQueueFunction($element) {
    return function(next) {
        $element.addClass("out");
        next();
    };
}

$('button').click(function() {
    var queue = $({}); //use the default animation queue
    $(".discrete").each(function() {
        queue.queue(createWorkQueueFunction($(this)));
        queue.delay(200);
    });
});

But why don't your examples work?

The reason why the following doesn't work is because jQuery will immediately add the 'out' class after adding a 200 ms delay to the fx queue. In other words, delay() will not pause items that are not added to a queue. Please see: What are queues in jQuery? for more information about how jQuery queues work.

$('.discrete').each(function() { $(this).delay(200).addClass('out'); });

In the second example, you're adding the same timeout to each of the .discrete elements. So after roughly 200ms each one will have a class added to it at just about the same time. Instead you probably would have wanted to set a timeout of 200ms, then 400ms, then 600ms and so on for each element.

$('.discrete').each(function() { var theNode = $(this);
setTimeout(function() { theNode.addClass('out'); }, 200); });




回答3:


I have created simple 2 line solution which works among all frameworks

let dl = 0.2; //time-delay // <animation class> <gap animation> document.querySelectorAll('.card.fade-in').forEach(o=>{dl+=0.2;o.style.animationDelay=dl+'s'});



来源:https://stackoverflow.com/questions/19072497/staggering-css-animations

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