javascript - 我们如何防止在 JavaScript 中在特定时间内一次又一次地单击按钮?
问题描述
所以在代码中,按下按钮会为红色框设置动画。单击该按钮将沿对角线移动它。但是如果我们在动画发生时再次单击该按钮或多次单击它会产生闪烁效果。我们如何解决这个问题?
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>
解决方案
您需要在动画正在进行时设置一个标志,并且在它仍在进行时不要执行该功能
var animationInProgress = false;
function myMove() {
if (animationInProgress) {
return;
}
var elem = document.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
animationInProgress = true;
function frame() {
if (pos == 350) {
animationInProgress = false;
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p><button onclick="myMove()">Click Me</button></p>
<div id="container">
<div id="animate"></div>
</div>
推荐阅读
- laravel - 如何使用嘲弄来模拟类的静态方法?
- python - 'admin-chat' 不是注册的命名空间
- python - Django URLS Slugs 多个路径
- python - 返回 TypeError:“LinearRegression”对象不可调用。此错误的其他答案说 LinearRegression 尚未初始化
- swift - 如何在我的视图控制器中向我的“全部删除”和“保存”按钮添加警报?
- powershell - AzureDevops 每次部署不同 IP 地址的分析服务
- java - 为列表中的所有对象设置相同的值,java?
- ios - GRU Pytorch Keras 和 Wiki 中的 Formula 不同
- php - php。如何读取一个文件,如果它用“a+”写入没有问题,但用“r”不可读?
- r - 如何在 data.table 中进行比较时包含“NA”的观察结果?