Jquery-stop动画函数后的setInterval

问题描述 投票:1回答:1

想法是在用户单击“开始”按钮后使用setinterval在循环中以顺时针方向移动div。当用户单击“停止”时,setInterval应该停止并返回其原始位置。我无法阻止这件事。谢谢。

$(document).ready(function() {
  var timer;

  $('#start').click(function() {
    timer = setInterval(function() {
      $("#animate").animate({
        'marginLeft': '200px'
      }, 2000)
      $("#animate").animate({
        'marginTop': '200px'
      }, 2000)
      $("#animate").animate({
        'marginLeft': '10px'
      }, 2000)
      $("#animate").animate({
        'marginTop': '0px'
      }, 2000)

    }, 50);

  });
});
$("#stop").click(function() {
  clearInterval(timer);
});
body {
  border: 1px solid blue;
  width: 237px;
  height: 263px;
}

div {
  margin: 7px;
  width: 40px;
  height: 40px;
  position: absolute;
  left: 0px;
  top: 30px;
  background: yellow;
}

div.newcolor {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="animate"></div>
jquery
1个回答
0
投票

首先,考虑到变量计时器超出了“停止”中附加事件的范围。此外,您必须考虑到,当您使用animate方法时,您每50毫秒将动画插入队列(因为您使用的是setInterval),因此您必须使用清除该队列的stop(true)。

看一下文档及其示例:https://api.jquery.com/stop/

var timer;
$(document).ready(function() {

  $('#start').click(function() {
    timer = setInterval(function() {
      $("#animate").animate({
        'marginLeft': '200px'
      }, 2000)
      $("#animate").animate({
        'marginTop': '200px'
      }, 2000)
      $("#animate").animate({
        'marginLeft': '10px'
      }, 2000)
      $("#animate").animate({
        'marginTop': '0px'
      }, 2000)

    }, 50);

  });
});
$("#stop").click(function() {
  $("#animate").stop(true);
  clearInterval(timer);
});
body {
  border: 1px solid blue;
  width: 237px;
  height: 263px;
}

div {
  margin: 7px;
  width: 40px;
  height: 40px;
  position: absolute;
  left: 0px;
  top: 30px;
  background: yellow;
}

div.newcolor {
  background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="animate"></div>
© www.soinside.com 2019 - 2024. All rights reserved.