[英]How to use more than one setInterval()?
我想讓代碼中的'box'向右移動然后再向左移動。 我試圖使用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>
作為替代方案,您還可以使用css動畫並完全跳過javascript部分:
@keyframes move { from { left: 0; } to { left: calc(100% - 50px); } } #container { width: 200px; height: 200px; background-color: red; position: relative; } #box { width: 50px; height: 50px; background-color: blue; position: absolute; animation: move 2s linear alternate infinite; }
<div id="container"> <div id="box"></div> </div> <p id="demo"></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.