如何让 .stop 工作并确保标题在我单击时停止,而不是在我单击的位置停止

how do i get .stop to work and make sure that the heading stops when i click and not where i click

本文关键字:单击 位置 标题 确保 工作 stop      更新时间:2023-09-26

如何使 .stop 使标题停止在我单击的位置。 并且不会因动画而移动。 仅使用 JavaScript。我需要标题在我单击的位置停止,但我需要单击标题以使其停止,这样我就无法单击任何地方,并且标题移动到那里然后停止,当我单击标题所在的位置时停止。

<!DOCTYPE html>
<html>
<head>
  <title>Interactive programming</title>
</head>
<body>
  <h1 id="heading" style="position:absolute;">Watch the moving heading!</h1>
  <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
  <script>
    function move() {
      $("h1").animate({
          "left": "+=200px"
        }, "slow")
        .animate({
          "top": "+=200px"
        }, "slow")
        .animate({
          "left": "-=200px"
        }, "slow")
        .animate({
          "top": "-=200px"
        }, "slow", function() {
          setInterval(move(),300)
        });
    }
    setInterval(move(),300)
    //this should stop it
    $("h1").click(function() {
    $("h1").stop();
    })
  </script>
  </body>
</html>

"setInterval"将继续运行,因此您将在 300 毫秒后启动一个新动画,即使您调用"stop"。

解决方案是将"setInterval"分配给var,然后您可以调用"clearInterval"。

          var interval = setInterval(move(),300);
    });
}
var setinterval = setInterval(move(),300);

现在您可以停止间隔:

$("h1").click(function() {
  clearInterval(interval);
  $('h1').stop();
}