2017-10-14 199 views
0

我想做一個簡單的onclick動畫。我onclicked按鈕應該向左移動,然後再點擊應該返回。我把clearInterval()放在了一些地方,但我看不到任何錯誤。你能幫助我嗎?爲什麼clearInterval()不能正常工作?


var backBack = document.getElementById('btn'); 
 
    var x = 0; 
 
    var loop = 'off'; 
 

 
    function push() { 
 
    if(loop == 'off') { 
 
    var t = setInterval(move,1); 
 
    } 
 
    if(loop == 'on') { 
 
    var t = setInterval(moveBack,1); 
 
    }} 
 

 
    function move() { 
 
    if(x < 500) { 
 
    x = x + 5; 
 
    backBack.style.left = x + 'px'; 
 
    clearInterval(t); 
 
    loop = 'on'; 
 
    }} 
 

 
    function moveBack() { 
 
    if(x > 0) { 
 
    x = x - 5; 
 
    backBack.style.right = x + 'px'; 
 
    clearInterval(t); 
 
    }}
 #btn { 
 
      position: absolute; 
 
      width: 50px; 
 
      height: 50px; 
 
      border-radius: 25px; 
 
      background-color: goldenrod; 
 
      border: none; 
 
      outline: none; 
 
     }
<button id="btn" onclick="push()" />

+1

'clearInterval(T);'應't'是未定義的外部引發錯誤'push' –

+0

@BrahmaDev但我需要它是有否則會不onclick事件執行 – CeeJay

回答

0

你必須把變量t的聲明之外的功能。 我做了一些改變,讓你的代碼工作。

它應該這樣做?

var backBack = document.getElementById('btn'); 
 
var x = 0; 
 
var loop = 'off'; 
 
var t; 
 

 
function push() { 
 
    if (loop == 'off') { 
 
    t = setInterval(move, 1); 
 
    } 
 
    if (loop == 'on') { 
 
    t = setInterval(moveBack, 1); 
 
    } 
 
} 
 

 
function move() { 
 
    if (x < 500) { 
 
    x = x + 5; 
 
    backBack.style.left = x + 'px'; 
 
    } else { 
 
    clearInterval(t); 
 
    loop = 'on'; 
 
    } 
 
} 
 

 
function moveBack() { 
 
    if (x > 0) { 
 
    x = x - 5; 
 
    backBack.style.left = x + 'px'; 
 
    } else { 
 
    clearInterval(t); 
 
    loop = 'off'; 
 
    } 
 
}
#btn { 
 
    position: absolute; 
 
    width: 50px; 
 
    height: 50px; 
 
    border-radius: 25px; 
 
    background-color: goldenrod; 
 
    border: none; 
 
    outline: none; 
 
}
<button id="btn" onclick="push()" />