为什么clearInterval()不能正常工作?

时间:2017-10-14 10:59:47

标签: javascript

我正在尝试制作一个简单的onclick动画。我的onclicked按钮应该向左移动,然后再次点击后应该返回。我放置clearInterval()的方式有问题,但我看不出任何错误。你能帮帮我吗?



var backBack = document.getElementById('btn');
    var x = 0;
    var loop = 'off';

    function push() {
    if(loop == 'off') {
    var t = setInterval(move,1);
    }
    if(loop == 'on') {
    var t = setInterval(moveBack,1);
    }}

    function move() {
    if(x < 500) {
    x = x + 5;
    backBack.style.left = x + 'px';
    clearInterval(t);
    loop = 'on';
    }}

    function moveBack() {
    if(x > 0) {
    x = x - 5;
    backBack.style.right = x + 'px';
    clearInterval(t);
    }}
&#13;
     #btn {
            position: absolute;
            width: 50px;
            height: 50px;
            border-radius: 25px;
            background-color: goldenrod;
            border: none;
            outline: none;
        }
&#13;
 <button id="btn" onclick="push()" />
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您必须在函数外部放置变量t的声明。 我做了一些更改以使代码正常工作。

它应该做这样的事情吗?

&#13;
&#13;
var backBack = document.getElementById('btn');
var x = 0;
var loop = 'off';
var t;

function push() {
  if (loop == 'off') {
    t = setInterval(move, 1);
  }
  if (loop == 'on') {
    t = setInterval(moveBack, 1);
  }
}

function move() {
  if (x < 500) {
    x = x + 5;
    backBack.style.left = x + 'px';
  } else {
    clearInterval(t);
    loop = 'on';
  }
}

function moveBack() {
  if (x > 0) {
    x = x - 5;
    backBack.style.left = x + 'px';
  } else {
    clearInterval(t);
    loop = 'off';
  }
}
&#13;
#btn {
  position: absolute;
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background-color: goldenrod;
  border: none;
  outline: none;
}
&#13;
<button id="btn" onclick="push()" />
&#13;
&#13;
&#13;