动画和动画防止多次点击动画

时间:2015-01-22 14:14:16

标签: javascript jquery

http://jsfiddle.net/ghv11Loy/

$('#wobble').click(function(){
  $(this).animate({marginLeft: '+10px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '-20px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '+10px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '-20px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '+10px'}, {"queue": true, "duration": 100});
});

当我多次点击#wobble时,动画会一直运行,直到它们完成。有没有办法防止这种情况发生?

例如,如果我尽可能快地点击它50次,我会等待动画运行50次。我希望能够点击一次,然后动画运行一次直到它完成。如果在动画停止后点击它等等,它可以再次运行。

另外,是否有一种更简洁的方法可以对元素进行多次动画处理,因为这看起来很混乱?

我已尝试使用.stop(),但我认为它并不适用于我所期待的。我可能做错了。

任何帮助都会很棒。

谢谢!

2 个答案:

答案 0 :(得分:2)

您需要在元素上调用stop(true, true)以结束当前正在运行或排队的所有动画:

$(this).stop(true, true)
    .animate({ marginLeft: '+10px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '-20px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '+10px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '-20px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '+10px' }, { "queue": true, "duration": 100 });

Example fiddle

答案 1 :(得分:1)

默认情况下,您可以设置某种全局布尔值,该值为false。一旦动画触发,验证它是否为假,动画,将其设置为true,然后仅在动画播放完毕后将其设置为假。

相关问题