2017-02-22 52 views
0

我試圖讓此功能無需重置即可重複使用。 例如,當我按下帶有此功能的按鈕時,按鈕將從0px移動到右側100px。當我再次按下按鈕時,它將從100px變爲200px,依此類推。它應該動畫,所以它一次移動1px直到循環結束。讓Javascript動畫繼續而不重置

下面的代碼只能作爲一次性使用,因爲它將從0px移動到100px,並再次按下它使其變爲0px到100px。

我一直在研究這個問題好幾個小時,並在詢問之前查看了很多來源的幫助。

function goRight() { 
    var pos = 0; 
    var count = pos; 
    var elem = document.getElementById("main"); 
    var id = setInterval(move, 5); 
    function move() { 
      if(pos == count + 100){elem.style.left = pos + 'px'; clearInterval(id);} 
      else {pos++; elem.style.left = pos + 'px';} 
    } 
} 
+0

你能告訴我你在哪裏調用函數嗎? –

+0

回答

1
function goRight() { 
    var elem = document.getElementById("main");     // the element 
    var origin = parseInt(elem.style.left) || 0;     // get the left of the element (as an origin for the animation), 0 if not set yet 
    var pos = 0;             // pos initialized to 0 

    var id = setInterval(move, 5); 
    function move() {           
     if(pos == 101) { clearInterval(id); }     // if pos is 101, then stop the animation 
     else { pos++; elem.style.left = (origin + pos) + 'px';} // if not, then increment it and set the left of the element to pos + origin 
    } 
} 
+0

謝謝。我沒有想到這樣使用parseInt,或者使用pos作爲值而不是像素數量。我的工作原理也是如此! –

+0

不客氣!訣竅是每次獲得'style.left'的值並添加到它的值,而不是從0開始再次... –

1

我想你只能做POS機作爲一個全局變量,並啓動它goRight功能

這樣外:

var pos = 0; 
function goRight() { 
    var count = pos; 
    var elem = document.getElementById("main"); 
    var id = setInterval(move, 5); 
    function move() { 
     if(pos == count + 100){elem.style.left = pos + 'px'; clearInterval(id);} 
     else {pos++; elem.style.left = pos + 'px';} 
    } 
} 

哪些錯誤在你的代碼是每次只你打電話goRight pos將被設置爲零,並且它將從頭開始。

但有一個全局變量它將被保存下一個時間間隔將運行。

+0

謝謝,這個工作方式我也很喜歡它,並且感覺很簡單。我愛工作幾小時後來到這裏,只感到啞巴xD –

+0

所以給我我的投票和接受請:) – Mahpooya