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


元素时,它开始晃动?

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

.HTML:

<!DOCTYPE html>
<html>
<head>
<title>Move</title>
<link rel="stylesheet" href="D:WebCSSCSS.css"/>
<script src="D:WebJSJS.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;
}

请帮助我 谢谢

您没有清除间隔,因为您没有将变量传递给它,因此它不会执行任何操作。如果将间隔设置为变量,则可以在切换方向时清除间隔。

参考: 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>

相关内容

最新更新