[英]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.