jquery 带点击事件的动画

jquery animation with click event

我想在动画中绑定一个点击事件,下面的代码是成功的,但是addscore()函数会做多一次,如何解决?

function moveObstacle(target,distance){
        target.removeClass('animated bounce');
        target.animate({ left: distance },{
            duration: 10000,
            progress: function(now, fx){
                $(this).addClass('animated bounce');
                $(this).click(function(){
                    $(this).hide();
                    addscore();
                });
            }
        }); 

    }


function addscore(){
        score2++;
        if(score2 == 10){
            score1++; score2 = 0;
        }
        $('.scoreNum').eq(0).html(score1);
        $('.scoreNum').eq(1).html(score2);
    }

您可以使用 bind() 和 unbind() 方法简单地解决它。如下所述更改您的代码。

$(this).unbind('click').bind('click'function(){
    $(this).hide();
    addscore();
});

您可以使用 'off' 和 'on' 功能来绑定和取消绑定您的活动:

$(this).off('click').on('click', function(){
    $(this).hide();
    addscore();
});

另一种方法是仅在动画开始时绑定事件(A.Wolff 建议)

 target.animate({
   left: distance
 }, {
   duration: 10000,
   start: function(fx) {
     $(this).click(function() {
       $(this).hide();
       addscore();
     });
   },
   progress: function(now, fx) {
     $(this).addClass('animated bounce');
   }
 });

一个选项是在进度函数之外分配点击事件处理程序并检查 :animated

不清楚你为什么需要 'animated bounce' class,所以留下这个,但问题似乎不需要 - 你可以用它来检查是否动画。

还添加了完成:时间到时隐藏目标的动作。

function moveObstacle(target,distance){
    target.removeClass('animated bounce');
    target.click(function() {
        if ($(this).is(":animated")) {
            $(this).hide();
            addscore();
        });
    });
    target.animate({ left: distance },{
        duration: 10000,
        progress: function(now, fx){
            $(this).addClass('animated bounce');
        },
        complete: function() {
            $(this).hide();
        }
    }); 
}

另一种方法是在开始时分配点击并在停止时将其移除:

function moveObstacle(target,distance){
    target.removeClass('animated bounce');
    target.click(function() {
        $(this).hide();
        addscore();
    });
    target.animate({ left: distance },{
        duration: 10000,
        progress: function(now, fx){
            $(this).addClass('animated bounce');
        },
        complete: function() {
            target.off("click");
        }
    }); 
}