簡體   English   中英

Clearinterval 方法無法清除 Rotation javascript 動畫

[英]Clearinterval method is unable to clear Rotation javascript animation

我是 JS 新手,我試圖在順時針旋轉的同時從左到右移動對象,在這里我應用了 setinterval 從左到右的移動動畫以及旋轉。 我可以清除從左到右的運動間隔,但無法清除我的旋轉間隔 我不知道為什么,如果您能看一下

 window.topPos = ''; var e = document.getElementById("aDiv"); var s = 1; var rotate = false; var degrees = 0; function myInterval() { var eLeftPos = e.offsetLeft; e.style.left = (eLeftPos + s) + 'px'; function rot() { degrees++; e.style.transform = 'rotate(' + degrees + 'deg)'; } var rotID = setInterval(rot, 1000) var leftPos = (eLeftPos + s) >= 1000 if ((eLeftPos + s) >= 1000) { clearInterval(rotID) console.log(rotID) } if ((eLeftPos + s) >= 1000) { clearInterval(internal) } } var internal = setInterval(myInterval, 100);
 #aDiv { background: black; width: 80px; height: 80px; position: relative; } #aDiv1 { background: red; width: 80px; height: 80px; position: absolute; }
 <div id="aDiv"></div> <button>Stop</button>

您無法從旋轉中清除間隔,因為每次執行第一個(移動)間隔時都會啟動一個新的setInterval 每 1000 毫秒您將有一個新的輪換間隔。 為什么不在同一個setInterval回調中移動和旋轉,然后只有 1 個要取消:

 window.topPos = ''; var e = document.getElementById("aDiv"); var s = 1; var rotate = false; var degrees = 0; function myInterval() { var eLeftPos = e.offsetLeft; var leftPos = (eLeftPos + s); // new left pos e.style.left = leftPos + 'px'; degrees++; e.style.transform = 'rotate(' + degrees + 'deg)'; if (leftPos >= 100) { // made 100 just to show the effect quicker clearInterval(internal) } } var internal = setInterval(myInterval, 100);
 #aDiv { background: black; width: 80px; height: 80px; position: relative; } #aDiv1 { background: red; width: 80px; height: 80px; position: absolute; }
 <div id="aDiv"></div> <button>Stop</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM