如何反转动画?

时间:2019-07-02 13:43:58

标签: javascript

第二次单击后,我试图将动画从上,左移到下,右。

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"; 
    }
  }

}

1 个答案:

答案 0 :(得分:0)

喜欢吗?

您也可以在单击某些内容时更改切换

var toggle = true

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

  function frame() {
    if (pos >= 350 || pos < 0) toggle = !toggle // remove this to use an event handler
    pos += (toggle ? 1 : -1)

    elem.style.top = pos + "px";
    elem.style.left = pos + "px";

  }

}
myMove()
#animate {
  position: absolute
}
<div id="animate">*</div>