为什么当我尝试移动<div>元素时,它会开始抖动?

时间:2018-08-25 17:24:49

标签: javascript html

我是Stack Overflow的新手。 我有一个简单的网页,试图来回移动彩色的div元素。 但是,当我运行它时,div元素开始正确移动,但是几秒钟后它开始疯狂地晃动,好像它的老板拒绝给它薪水。 这是我的代码:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Move</title>
    <link rel="stylesheet" href="D:\Web\CSS\CSS.css"/>
    <script src="D:\Web\JS\JS.js">
    </script>
    </head>
    <body>
        <div id="container">
            <div id="box">
            </div>
        </div>
    </body>
</html>

JavaScript:

window.onload = function() {

  var x = 0;

  var box = document.getElementById("box");
  setInterval(moveRight, 5);

  function moveRight() {
    if(x >= 150) {
      clearInterval();
      setInterval(moveLeft, 5);
    } else {
      x += 1;
      box.style.left = x + "px";
    }
  }

  function moveLeft() {
    if(x <= 0) {
      clearInterval();
      setInterval(moveRight, 5);
    } else {
      x -= 1;
      box.style.left = x + "px";
    }
  }

}

CSS:

body {
  background-color: #246;
}

#container {
  width: 200px;
  height: 50px;
  background: #268;
  position: relative;
}

#box {
  width: 50px;
  height: 50px;
  background: #2ac;
  position: absolute;
}

请帮助我 谢谢

1 个答案:

答案 0 :(得分:1)

您没有清除间隔,因为您没有向其传递变量,因此它没有做任何事情。如果将间隔设置为变量,则可以在切换方向时清除间隔。

参考:https://www.w3schools.com/jsref/met_win_clearinterval.asp

这是一个例子:

(function() {
  var direction;
  var x = 0;
  var box = document.getElementById("box");

  // set the initial direction
  direction = setInterval(moveRight, 5);

  function moveRight() {
    if (x >= 150) {
      clearInterval(direction);
      direction = setInterval(moveLeft, 5);
    } else {
      x += 1;
      box.style.left = x + "px";
    }
  }

  function moveLeft() {
    if (x <= 0) {
      clearInterval(direction);
      direction = setInterval(moveRight, 5);
    } else {
      x -= 1;
      box.style.left = x + "px";
    }
  }
})();
body {
  background-color: #246;
}

#container {
  width: 200px;
  height: 50px;
  background: #268;
  position: relative;
}

#box {
  width: 50px;
  height: 50px;
  background: #2ac;
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
  <title>Move</title>
</head>

<body>
  <div id="container">
    <div id="box">
    </div>
  </div>
</body>

</html>