用javascript重设一个简单的动画

问题描述 投票:1回答:1

我想用javascript做一个简单的动画。我想在按下 "Click Me "按钮时启动动画,再按一次使其复位,再按第三次使其重启。

我粘贴的代码在重置动画后停止工作。我到底做错了什么?

我试图添加一些日志来跟踪我的变量,但我真的不明白这个问题。

var terminateConditionFullfiled;

function ClickManager() {
  var elem = document.getElementById("animate");
  var pos_top = elem.style.top;
  var pos_left = elem.style.left;
  if (pos_top != 0 && pos_left != 0) {
    elem.style.top = 0 + "px";
    elem.style.left = 0 + "px";
    terminateConditionFullfiled = true;
    WritePosition(elem);
    var tt = document.getElementById("tt");
    tt.innerHTML = "terminateConditionFullfiled = " + terminateConditionFullfiled;
  } else {
    terminateConditionFullfiled = false;
    myMove();
    var tt = document.getElementById("tt");
    tt.innerHTML = "terminateConditionFullfiled = " + terminateConditionFullfiled;
  }
}

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

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

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

  function frame() {
    if (terminateConditionFullfiled) {
      return;
    }
    if (pos == 0) {
      clearInterval(id);
      myMove();
    } else {
      pos--;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
      WritePosition(elem)
    }
  }
}

function WritePosition(elem) {
  var log = document.getElementById("log");
  log.innerHTML = elem.style.top + " " + elem.style.left;
}
#container {
  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}

#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
<p><button onclick="ClickManager()">Click Me</button></p>
<p id="log">Log is here </p>
<p id="tt">terminateConditionFullfiled = </p>
<div id="container">
  <div id="animate"></div>
</div>
javascript animation button css-animations
1个回答
0
投票

问题来自于你的条件 if (pos_top != 0 && pos_left != 0). 在这里你应该看看你的变量的内容。pos_toppos_left.

在第一次点击时,内容是 "" (一个空字符串),它在你的条件中返回true。找出原因.

在第二次和第三次点击时,你可能有 pos_top == 123px. 重要的是要看到有 px 在最后添加。这将导致你的条件始终是 true 因此,它只在第一次工作。

你可以用一个全局变量 running 其中设置为 true 当动画运行和 false 的值。

下面是一个小例子,它打印出的值为 pos_top 前后通过javascript定义。

let box = document.getElementById("animate")
console.log("The actual position of the box is: " + box.style.top)
console.log("Let's specify the position now through JS")
box.style.top = "20px"
console.log("The actual position of the box is: " + box.style.top)
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
<div id="animate"></div>

0
投票

所以,如果我理解,你希望在第二次点击复位动画时,对象达到(0,0)?

© www.soinside.com 2019 - 2024. All rights reserved.