【问题标题】:Staggering CSS Animations交错的 CSS 动画
【发布时间】:2019-12-06 02:39:15
【问题描述】:

我有一个 CSS 动画,我想以 200 毫秒的间隔应用。我已经这样设置了 CSS:

.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;    
}

然后我想以 200 毫秒的间隔错开 .discrete.out 类的应用。我尝试了以下方法:

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

还有这个:

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

但在这两种情况下,动画都是一次性发生的!

有什么想法吗?

【问题讨论】:

    标签: javascript jquery css css-animations


    【解决方案1】:

    你可以使用

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

    Demo

    【讨论】:

    • 将此方法标记为已接受,因为这种方法似乎比使用 jQuery 动画队列快得多!谢谢大家!
    【解决方案2】:

    尝试使用 jQuery 动画队列: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);
        });
    });
    

    但为什么你的例子不起作用?

    下面这个不起作用的原因是,jQuery 会在给 fx 队列添加 200 毫秒延迟后立即添加 'out' 类。换句话说, delay() 不会暂停未添加到队列中的项目。有关 jQuery 队列如何工作的更多信息,请参阅:What are queues in jQuery?

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

    在第二个示例中,您为每个 .discrete 元素添加了相同的超时。因此,大约 200 毫秒后,每个人将几乎同时添加一个类。相反,您可能希望为每个元素设置 200 毫秒、400 毫秒、600 毫秒等等的超时时间。

    $('.discrete').each(function() { var theNode = $(this);
    设置超时(函数(){ theNode.addClass('out'); }, 200); });

    【讨论】:

      【解决方案3】:

      我创建了适用于所有框架的简单 2 行解决方案

      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'});

      【讨论】:

        猜你喜欢
        • 2016-09-20
        • 2018-04-05
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        • 2016-05-12
        • 2016-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多