【发布时间】:2015-07-29 09:22:15
【问题描述】:
我正在尝试为单击事件的按钮创建动画。动画使用了一个简单的函数,它只包含切换类和设置超时。
它适用于一个按钮,但是当我有多个按钮并且在动画完成之前连续单击两个或多个按钮时,动画会停止并继续在稍后单击的元素上。
所以问题是让动画函数引用触发它的对象,因此创建它的多个实例,经过数小时的搜索,我无法找到一个简单的解决方案)。
提前致谢。
有一个简化的例子(真实例子有更多的类切换):
$('.myButton').on('click', animateButton);
function animateButton(){
var $this = $(this);
$this.addClass('animate');
setTimeout(function(){
$this.removeClass('animate');
},2000)
}
编辑:我做了一个小提琴:https://jsfiddle.net/8ozu14am/
EDIT2:已解决
使用 $.proxy() 可以维护上下文。
$('.myButton').on('click', animateButton);
function animateButton(){
$(this).addClass('animate');
setTimeout($.proxy(function(){
$(this).removeClass('animate');
},this),2000)
}
【问题讨论】:
标签: javascript jquery animation