gpt4 book ai didi

javascript - 如何使用多个setInterval()?

转载 作者:行者123 更新时间:2023-11-30 11:01:13 28 4
gpt4 key购买 nike

我想让代码中的“框”向右移动,然后再向左移动。我尝试使用 2 个 setInterval,但它不起作用(或者我可能不知道如何使用 2 个 setInterval)。

var box = document.getElementById("box");
var pos = 0;
var toRight = setInterval(move, 10);

function move() {
if (pos >= 150) {
clearInterval(toRight);
} else {
pos++;
box.style.left = pos + "px";
}
}
#container {
width: 200px;
height: 200px;
background-color: red;
position: relative;
}

#box {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
}
<div id="container">
<div id="box"></div>
</div>
<p id="demo"></p>

我尝试了很多方法,代码仍然无法运行,谁能告诉我如何让“盒子”从右侧移回。谢谢。

最佳答案

您的代码是一个好的开始,@j08691 的评论是正确的方向。

使用 1 个间隔函数,但要跟踪盒子移动的方向并在需要时切换它。

let box = document.getElementById("box");
let pos = 0, right = true;
setInterval(() => {
pos += right * 2 - 1;
if (pos === 0 || pos === 150)
right = !right;
box.style.left = pos + "px";
}, 10);
#container {
width: 200px;
height: 200px;
background-color: red;
position: relative;
}

#box {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
}
<div id="container">
<div id="box"></div>
</div>

关于javascript - 如何使用多个setInterval()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57631560/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com