不要拍摄新的动画,直到当前没有结束

Do not shoot new animation until the current does not end

本文关键字:结束 动画      更新时间:2023-09-26

我有一个跳跃动画

$("#bounce").click(function() {
    doBounce($(this), 3, '10px', 300);       
});

function doBounce(element, times, distance, speed) {
    for(i = 0; i < times; i++) {
        element
            .animate({marginTop: '-='+distance},speed)
            .animate({marginTop: '+='+distance},speed);
    }        
}

但是,当我在元素上单击几次时,各种动画开始,从而形成事件堆栈。我想点击,而当前动画没有结束,不可能启动其他镜头,即使我点击元素。如何做到这一点?

一个解决方案是使用:animated选择器:

function doBounce(element, times, distance, speed) {
    if (element.is(":not(:animated)")) {
        for(i = 0; i < times; i++) {
            element
                .animate({marginTop: '-='+distance},speed)
                .animate({marginTop: '+='+distance},speed);
        }
    }        
}

有几种方法,但我建议您使用Javascript scope设置一个bool值,如果动画完成,返回true。看到这个提琴和点击测试几次,当它是动画。

(function () {
    var animate = true;
    $("#bounce").click(function () {
        // Only fire when true, which it is by default.
        if (animate) {
            doBounce($(this), 3, '10px', 300);
        }
    });

    function doBounce(element, times, distance, speed) {
        // Set to false to prevent new calls. 
        animate = false;
        for (i = 0; i < times; i++) {
            element.animate({
                marginTop: '-=' + distance
            }, speed)
                .animate({
                marginTop: '+=' + distance
            }, speed);
        }
        // Set the var back to true after animations are finished.
        // https://api.jquery.com/promise/
        element.promise().done(function () {
            animate = true;
            alert(animate);
        });
    }
})();

另一个解决方案是节流功能。节流函数封装另一个(子)函数,并防止每n毫秒调用一次以上的子函数。下面是一个使用lodash库的示例:

var doBounce = _.throttle(function(element, times, distance, speed) {
    // here, put your original doBounce code
}, lengthOfAnimation);

现在,无论你调用doBounce(/* some arguments */);多少次,实际的代码将不会运行超过一次每lengthOfAnimation毫秒。

当然,这只会在每次动画长度相同的情况下起作用。

lodash: https://lodash.com/
节流:https://lodash.com/docs油门