[英]How do use setInterval() the correct way?
我对 javascript 相当陌生,当我单击“setInterval”按钮时,我试图让框#aDiv 每秒移动一些像素,并在我按下“setTimeout”按钮时让它停止。 我不知道在名为“move”的 function 中写什么而不会出现任何错误。 如果有人可以指导我或帮助我,我将不胜感激。
这是我的代码
<html lang="en">
<head>
<style>
#aDiv{
background-color: yellow;
width: 150px;
height: 150px;
position: absolute;
left: 10px;
top: 200px;
border-radius: 20px;
box-shadow: 2.5px 2.5px 5px 2.5px black;
}
</style>
</head>
<body>
<button type="button" onclick="setInterval()">Set interval</button><br>
<button type="button" onclick="">Set timeout</button><br>
<button type="button" onclick="myTimeoutFunction"> Clear timeout</button><br>
<button type="button" onclick=myStopFunction""> Clear interval</button><br>
<div id="aDiv"></div>
<script>
var event = document.getElementById("aDiv");
var second = 1;
var myVar;
function setInterval(){
myVar = setInterval(move,1000);
}
function move(){
var eLeftPos = event.offsetLeft;
event.style.left = (eLeftPos + second) + 'px';
}
function moveX(){
document.getElementsByClassName("box").left = 100;
}
function myTimeoutFunction() {
clearTimeout(myVar);
}
function myStopFunction() {
clearInterval(myVar);
}
</script>
</body>
</html> ```
正如已经说过的,你不应该命名你的 function setInterval
。 您正在覆盖浏览器的setInterval
function 并且它无限期地调用自己。 此外,您的event
变量包含一个没有意义的 DOM 元素。 为什么不将其命名为elem
?
一个好习惯也是不要直接在 HTML ( onclick="..."
) 中添加事件侦听器。
我不完全确定我理解你的问题,这是你想要做的吗? (点击代码下方蓝色按钮试一试)
var startBtn = document.getElementById("start-btn"), pauseBtn = document.getElementById("pause-btn"), resetBtn = document.getElementById("reset-btn"), elem = document.getElementById("aDiv"), second = 1, myInterval; startBtn.addEventListener('click', startAnimation); pauseBtn.addEventListener('click', pauseAnimation); resetBtn.addEventListener('click', resetAnimation); function startAnimation(){ // We don't want it to run multiples times in parallel pauseAnimation(); myInterval = setInterval(move, 50); } function pauseAnimation(){ clearInterval(myInterval); } function resetAnimation(){ pauseAnimation(); elem.style.left = '10px'; } function move(){ var eLeftPos = elem.offsetLeft; elem.style.left = (eLeftPos + second ) + 'px'; }
#aDiv{ background-color: yellow; width: 50px; height: 50px; position: absolute; left: 10px; top: 50px; border-radius: 20px; box-shadow: 2.5px 2.5px 5px 2.5px black; }
<button type="button" id="start-btn">Start</button> <button type="button" id="pause-btn">Pause</button> <button type="button" id="reset-btn">Reset</button> <div id="aDiv"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.