首页 > 解决方案 > 我们如何防止在 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>

标签: javascripthtmlcssdebugginganimation

解决方案


您需要在动画正在进行时设置一个标志,并且在它仍在进行时不要执行该功能

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>


推荐阅读