我有一个按钮,当点击时,动画一个div。
我试图利用$.animate() [complete]回调函数,但遇到的情况是,点击按钮两次真的很快导致动画运行两次之前,第一个动画的[complete]回调运行。
请参阅此链接进行演示。http://jsfiddle.net/zs2uf/3/
任何想法如何防止第二次点击击败第一次的回调?
你应该在点击按钮后立即禁用按钮,然后再做动画。
你说你想让按钮只能被点击一次,但是你等到动画完成后才禁用按钮。这就是为什么程序的行为不像你希望的那样,因为在动画期间,按钮可以再次点击。
这里是如何确保按钮只能被点击一次:
$("#next").click(function(){
var pos = parseInt($("#box").css("left")),
newPos = pos + 100;
// disable button immediately after the click
// if you wait to disable, you give the user the chance to click twice
$("#next").unbind('click');
$("#next").attr("disabled", "disabled");
$("#box").animate({
"left" : newPos //move the box to the right by 100px
}, {
duration: 150
});
})
工作示例
unbind()
在许多浏览器中可能不是必需的,但它确保了click事件处理程序实际上从#next
中删除。
修复了,看看这个
http://jsfiddle.net/zs2uf/5/$("#next").click(function(){
var pos = parseInt($("#box").css("left"));
var newPos = pos + 100;
if($("#box:animated").length == 0){
$("#box").animate({
"left" : newPos //move the box to the right by 100px
}, {
duration: 150,
complete: function(){
//after moving the box by 100px, disable the next button,
//so that the box can move no further than 100px
$("#next").attr("disabled", true);
}
});
}
//problem:
//if you click the Next button twice really fast,
//the box moves twice before the button is disabled
})