我想将盒子移到拐角处(水平从左上角
角到右上角,然后向下到右下角。



function myMove() {
  var elem = document.getElementById("animate");
  var pos = 0;
  var id = setInterval(frame, 5);

  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
    }
  }
}

#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}

#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}

<p><button onclick="myMove()">Click Me</button></p>

<div id="container">
  <div id="animate"></div>
</div>

最佳答案

您可以按照以下条件将topleft的距离设置为有条件,以使其每次都在一个方向上移动,并在总移动距离满足该位置时停止:



function myMove() {
  var elem = document.getElementById("animate");
  var left = 0;
  var top = 0;
  var id = setInterval(frame, 5);
  elem.style.left = "0px";
  elem.style.top = "0px"

  function frame() {
    if (left < 350 && top == 0) {
      left++;
      elem.style.left = left + "px";
    } else if (left == 350 && top < 350) {
      top++;
      elem.style.top = top + "px";
    } else if (top == 350 && left > 0) {
      left--;
      elem.style.left = left + "px";
    }
    else {
      clearInterval(id);
    }
  }
}

#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}

#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}

<p><button onclick="myMove()">Click Me</button></p>
<div id="container">
  <div id="animate"></div>
</div>

10-04 11:10