2017-03-02 114 views
-1

我試圖創建一個動畫框,它將像這樣移動 - 點擊開始按鈕,向右,然後是底部,左側和頂部。點擊停止按鈕時,不管它是什麼,它都會停止移動,然後在再次點擊開始時重新拾起。我設法讓它工作,當它從左到右,然後從右到左,但是當我試圖創建整個循環(左 - >右 - >底部 - >右 - >頂部),我'米麪臨的問題。我究竟做錯了什麼?通過一個快速無限循環

代碼:

var pos = 0; 
var pos1 = 0; 
var s = document.getElementById("start"); 
var st= document.getElementById("stop"); 
s.addEventListener("click",btstart); 
st.addEventListener("click",btstop); 
var t, t1; /*t and t1 should be global variables so they can be accessed by the btstop function*/ 
function btstart(){ 
    var box = document.getElementById('box'); 
    t = setInterval(movel, 10); 
} 

function movel() { 
    if(pos >= 150) { 
     t = setInterval(moveb, 50); 
    } 
    else { 
     pos += 1; 
     box.style.left = pos+'px'; 
    } 
} 

function moveb(){ 
    if (pos1 >= 150) 
    { 
     t = setInterval(mover, 50); 
    } 
    else { 
     pos1 += 1; 
     box.style.top = pos1+'px'; 
    } 
} 
function mover() { 
    if(pos === 0) { 
     t = setInterval(movet, 50); /*Note: clearing t, not t1. Ends the function/script completely*/ 
    } 
    else { 
     pos -= 1; 
     box.style.right = pos+'px'; 
    } 
} 
function movet(){ 
    if (pos1 === 0) 
    { 
     t = setInterval(movel, 50); 
    } 
    else { 
     pos1 -= 1; 
     box.style.bottom = pos1+'px'; 
    } 
} 

function btstop() { 
    clearInterval(t); 
    /*clearInterval(t1);*/ 
} 
/*var box = document.getElementById("box");*/ 
+2

然後告訴我們你的代碼,問題出在哪裏 – Weedoze

+1

剛添加的代碼。我是新來的,在粘貼代碼之前,我不小心點擊了帖子。 –

回答

0

這裏是你的代碼一點點清晰。我只用一個時間間隔,將檢查當前的位置,然後用setAndMove移動框和保存位置

var box = document.getElementById("box"); 
 
var startButton = document.getElementById("start"); 
 
var stopButton = document.getElementById("stop"); 
 
startButton.addEventListener("click", start); 
 
stopButton.addEventListener("click", stop); 
 

 
var interval; 
 
var horizontal = 0; 
 
var vertical = 0; 
 
var space = 50; 
 

 
function start() { 
 
    interval = setInterval(function() { 
 
    if (horizontal === 0 && vertical === 0) { 
 
     //box is top left 
 
     setAndMove(space, 0, 'left', space); 
 
    } else if (horizontal === space && vertical === 0) { 
 
     //box is top right 
 
     setAndMove(space,space, 'top', space); 
 
    } else if (horizontal === space && vertical === space){ 
 
     //box is bottom right 
 
     setAndMove(0,space, 'left', 0); 
 
    } else if(horizontal === 0 && vertical === space){ 
 
    //box is bottom left 
 
     setAndMove(0,0, 'top', 0); 
 
    } 
 
    }, 1000); 
 
} 
 

 
function stop() { 
 
    clearInterval(interval); 
 
} 
 

 
function setAndMove(hori, vert, direction, directionValue){ 
 
    horizontal = hori; 
 
    vertical = vert; 
 
    box.style[direction] = directionValue + "px"; 
 
}
#box { 
 
    width: 20px; 
 
    height: 20px; 
 
    background-color: red; 
 
    position: fixed; 
 
} 
 
#start{ 
 
    margin-top: 100px; 
 
}
<div id="box"></div> 
 

 
<button id="start">Start</button> 
 
<button id="stop">Stop</button>