我想讓一個元素(id=runner)在滑鼠懸停事件后在頁面上移動 n 個像素,然后停在某個位置(左 = 2000px),使用 setInterval() 重復呼叫 move_left(),然后 clearInterval()當左 == 200px 時。我可以讓元素移動,但是當我查看開發人員工具時,它永遠不會停止 - 左繼續增加。我對 JavaScript/HTML/CSS 很陌生。我如何讓它停止?
相關代碼:
<script>
function runner_go()
{
var load_time = performance.now();
const go = setInterval(move_left,20);
}
function move_left()
{
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position,10) 17 "px";
if (parseInt(runner_position,10) > 2000)
{
clearInterval(go);
}
}
</script>
</head>
<body style="background-color:gray;" onmouseover = "runner_go();">
<div>
<h1>Running!</h1>
</div>
<img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/>
</body>
uj5u.com熱心網友回復:
問題 -
- 您將區間變數宣告為另一個函式中的常量,而 move_left 函式無法訪問該函式
所以只需將您的區間變數移動到全域范圍(在函式之外),它應該可以作業
let go;
function runner_go() {
var load_time = performance.now();
go = setInterval(move_left, 20);
}
function move_left() {
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position, 10) 17 "px";
if (parseInt(runner_position, 10) > 2000) {
clearInterval(go);
}
}
間隔和 clearIntervals 如何作業的示例
let interval, i = 1;
function start() {
interval = setInterval(log, 1000);
}
function log() {
if (i >= 5) clearInterval(interval);
console.log(`Test ${i}`);
i
}
start();
uj5u.com熱心網友回復:
您需要在范圍的方法原因之外創建 var 'go',此外,如果您讓 'body' 為 'onmouseover',它每次都會設定間隔。
試試這個代碼來測驗:
<head>
<script>
let go = null;
function runner_go()
{
var load_time = performance.now();
go = setInterval(move_left,20);
}
function move_left()
{
document.getElementById('runner').style.visibility = "visible";
var runner_position = getComputedStyle(document.getElementById('runner')).getPropertyValue('left');
document.getElementById('runner').style.left = parseInt(runner_position,10) 17 "px";
if (parseInt(runner_position,10) > 2000)
{
clearInterval(go);
}
}
</script>
</head>
<body style="background-color:gray;" onclick = "runner_go();">
<div>
<h1>Running!</h1>
</div>
<img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/> </body>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/325178.html
標籤:javascript html 设置间隔 清除间隔
