添加点击处理程序,并使用 clearIntervals 取消间隔

Add Click handler, and Cancel intervals with clearIntervals

我添加了 fadeOutfadeIn 以查看我的点击处理程序是否有效并且确实有效。如何添加点击处理程序来取消动画?如何使用 clearInterval 函数取消间隔?

var offset = 0;
var direction = "left";
var moveHeading = function() {
  if (direction === "left") {
    $('#heading').offset({
      left: offset
    });
    offset += 2;
    if (offset > 400) {
      direction = "down";
      offset = 0;
    }
  } else if (direction === "down") {
    $('#heading').offset({
      top: offset
    });
    offset += 2;
    if (offset > 400) {
      direction = "right";

    }
  } else if (direction === "right") {
    $('#heading').offset({
      left: offset
    });
    offset -= 2;
    if (Math.abs(offset) <= 0) {
      direction = "up";
      offset = 0;
    }
  } else if (direction === "up") {
    $('#heading').offset({
      top: offset
    });
    offset -= 2;
    if (Math.abs(offset) > 200) {
      direction = "left";
      offset = 0;
    }
  }
};

setInterval(moveHeading, 30);

$(document).ready(function() {
  $("#heading").click(function() {
    $(this).fadeOut(3000).fadeIn(3000);
  })
})

clearInterval(moveHeading);
<h1 id="heading">Hola mi gente!! Como esta?</h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>

要在单击 #heading 时停止动画,您需要存储从 setInterval() 调用返回的 ID,然后将其提供给单击事件处理程序中的 clearInterval() 调用。试试这个:

var offset = 0;
var direction = "left";
var moveHeading = function() {
  if (direction === "left") {
    $('#heading').offset({
      left: offset
    });
    offset += 2;
    if (offset > 400) {
      direction = "down";
      offset = 0;
    }
  } else if (direction === "down") {
    $('#heading').offset({
      top: offset
    });
    offset += 2;
    if (offset > 400) {
      direction = "right";

    }
  } else if (direction === "right") {
    $('#heading').offset({
      left: offset
    });
    offset -= 2;
    if (Math.abs(offset) <= 0) {
      direction = "up";
      offset = 0;
    }
  } else if (direction === "up") {
    $('#heading').offset({
      top: offset
    });
    offset -= 2;
    if (Math.abs(offset) > 200) {
      direction = "left";
      offset = 0;
    }
  }
};

let interval = setInterval(moveHeading, 30);

$(document).ready(function() {
  $("#heading").click(function() {
    $(this).fadeOut(3000).fadeIn(3000);
    clearInterval(interval);
  })
})
<h1 id="heading">Hola mi gente!! Como esta?</h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>