为什么这个元素不以一致的速度移动?

Why does this element not travel at a consistent speed?

我正在制作一个程序,以每秒 50 像素的速度将元素移动到随机点(并在到达该点后循环)。我算了一下,但它的行进速度不一致。

// for some reason i need to put all the code in a function, so that's what this bit is
window.onload = doit;

function doit() {
  var dief = document.getElementById('he');

  //chooses a random number within the width of the page (px):
  var mh = Math.floor(Math.random() * window.innerWidth);

  //sets the time it should take to travel the random distance going 50px per second (t=d/v):
  time = mh / 50

  //this sets the amount of time it takes for the transition from one point to another to occur:
  dief.style.transition = "left " + time + "s linear";

  //this sets the position:
  dief.style.left = mh + "px";
  setTimeout(doit, time * 1000);
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>

<body>
  <div id="he" style="position: absolute; left: 0px;">hey</div>
</body>

</html>

行进距离不是 mh。它是 mh 减去元素的当前 left

您可以这样做:

window.onload = () => doit(0);

function doit(currentLeft) {
  var dief = document.getElementById('he');
  var mh = Math.floor(Math.random() * window.innerWidth);
  var time = Math.abs(mh - currentLeft) / 50
  dief.style.transition = "left " + time + "s linear";
  dief.style.left = mh + "px";
  setTimeout(() => doit(mh), time * 1000);
}
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>

<body>
  <div id="he" style="position: absolute; left: 0px;">hey</div>
</body>

</html>