经历快速无限循环

时间:2017-03-02 07:32:01

标签: javascript animation

我试图创建一个像这样移动的动画框 - 点击开始按钮,向右,然后向下,向左和向上。点击停止按钮后,无论它是什么,它都会停止移动,然后再次点击开始时再回来。

当它刚刚从左到右然后从右到左时,我设法让它工作,但当我尝试创建整个循环时(左 - >右:>底部>右 - >顶部) ,我遇到了问题。我究竟做错了什么?

代码:

 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");*/

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;