我刚刚开始接触 jQuery 和 Web 开发,所以请原谅任何幼稚的错误。我正在尝试有一个按钮可以导致动画发生。也就是说,这个动画只是将“h2”标题从左向右移动,然后再返回(并简单地更改颜色)。
我在使用以下代码时遇到的问题是,如果用户多次单击该按钮,则会导致该按钮继续经过周转点。我了解到这是一个异步问题,并尝试在动画调用中使用回调函数来重新启用按钮功能。
如您所见,我已通过设置queue:false 变量解决了该问题。由于我对此还是新手,有没有更简单的方法来做到这一点?
感谢您的帮助!
var toTheRight = true;
$('#animation').click(function () {
var header = $('h2')[0].style.left.toString();
var headerNum;
if (header.length < 5) {
headerNum = 0;
}
else {
headerNum = +(header.substring(0, header.length - 2));
}
if (headerNum >= 450) {
toTheRight = false;
$('h2').css("background-color", "green");
}
if (headerNum < 100) {
toTheRight = true;
$('h2').css("background-color", "orange");
}
var modified;
var stringified;
if (toTheRight) {
modified = Math.round((headerNum + 100) / 100) * 100;
strigified = modified + "px";
$('h2').animate({
"font-size": "3em",
"width": "50%",
"left": stringified
}, { queue: false, duration: 1000 });
}
else {
modified = Math.round((headerNum - 100) / 100) * 100;
stringified = modified + "px";
$('h2').animate({
"font-size": "3em",
"width": "50%",
"left": stringified
}, { queue: false, duration: 1000 });
}
});
最佳答案
您可以将函数包装在 if 中,如下所示:
$('#animation').click(function () {
if(!$('h2').is(':animated')){
//your function
}
})
编辑:
正如烤所说,你可以这样做:
$('#animation').click(function () {
if($('h2').is(':animated')) return;
//your function
})
关于jquery - 防止 onClick 事件多次发生 (jQuery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16949262/