2017-03-02 113 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>