首页 > 解决方案 > 无法在 JQuery 中禁用动画

问题描述

我想在用户选中复选框后禁用动画,但我无法让它工作。

 function onChangeTarget(num) {
            updateCounter();
            if (num != 0) {
                targetHideAnimation = parseInt(num);
                $('div.plus-point.plus-point' + num + '').css("display", "block");
                $('div#wrap-' + num + ' img').css("filter", "grayscale(1)");
                if (targetHideAnimation != 0) {
                    $('div#wrap-' + num + '').stop();
                }
            }
        } 

这是我的完整源代码: https ://jsfiddle.net/ninhnguyen2208/o4htr5xj/

请告诉我我错过了什么。

标签: javascripthtmljquery

解决方案


看看你的小提琴,问题不在于.stop(),而在于.animate,特别是回调:

     function upDown() {
        for (var i = 1; i <= QTY_TARGETS; i++) {
            ...
            wrap.animate({ 'top': '' + moveTop + 'px' }, {
                duration: duration,
                complete: function () {
                    wrap.animate({ top: '' + moveTopRepeat + '' },
                    {
                        duration: duration,
                        // this line here
                        complete: upDown
                    });
                }
            });
        }
    }

重新启动upDown complete:upDown,但在每个目标中称为 form 并调用外部 upDown All

将 upDown 分离为 upDownAll 和一个内部 upDownTarget 然后在单个目标上为该目标完全重置:

    function upDown() {
        for (var i = 1; i <= QTY_TARGETS; i++) {
            upDownTarget(i)
        }
    }
    function upDownTarget(i)
    {
      ...
      wrap.animate({ 'top': '' + moveTop + 'px' }, {
        duration: duration,
        complete: function () {
          wrap.animate({ top: '' + moveTopRepeat + '' },
                       {
            duration: duration,

            // only restart this one target
            complete: function() { upDownTarget(i) }
          });
        }
      });
    }

更新小提琴: https ://jsfiddle.net/29hntbve/


另外,您还可能希望在玩家失败时停止动画:

res.text('You lose');
$(".wrap").stop();

推荐阅读