JavaScript 逐渐减慢动作无法正常工作:
JavaScript Gradually Slowing Motion Not Working Properly:
下面的代码应该每秒将元素“box”向下移动“speed”像素,而“speed”应该每秒减少 0.1。这应该给人一种运动减慢的错觉。如果有人知道如何修复此代码 - 或提供不同的解决方案 - 将不胜感激。
function move() {
var pos = 318;
for (var speed = 5; speed > 0; speed -= 0.1) {
setTimeout(function() {
pos -= speed;
document.getElementById("box").style.bottom = pos + "px";
}, 1000);
}
}
for 循环中的 setTimeout 实际上并没有像您期望的那样在迭代之间创建延迟,而是它只是在一秒后执行所有函数。相反,您应该在 move()
函数内部创建另一个函数,该函数使用 setTimeout()
调用自身,或者使用 setInterval()
.
使用 setTimeout:
function move() {
var pos = 0;
var speed = 5;
function moveBox() {
if (speed <= 0) {console.log("done"); return;}
speed -= 0.1;
pos += speed; // done backwards for visibility
document.getElementById("box").style.top = pos + "px";
setTimeout(moveBox, 25) //sped up for convenience
}
moveBox();
}
move();
#box {
position: absolute;
height: 1em;
width: 1em;
background-color: black;
}
<div id="box" style="bottom: 318px"></div>
下面的代码应该每秒将元素“box”向下移动“speed”像素,而“speed”应该每秒减少 0.1。这应该给人一种运动减慢的错觉。如果有人知道如何修复此代码 - 或提供不同的解决方案 - 将不胜感激。
function move() {
var pos = 318;
for (var speed = 5; speed > 0; speed -= 0.1) {
setTimeout(function() {
pos -= speed;
document.getElementById("box").style.bottom = pos + "px";
}, 1000);
}
}
for 循环中的 setTimeout 实际上并没有像您期望的那样在迭代之间创建延迟,而是它只是在一秒后执行所有函数。相反,您应该在 move()
函数内部创建另一个函数,该函数使用 setTimeout()
调用自身,或者使用 setInterval()
.
使用 setTimeout:
function move() {
var pos = 0;
var speed = 5;
function moveBox() {
if (speed <= 0) {console.log("done"); return;}
speed -= 0.1;
pos += speed; // done backwards for visibility
document.getElementById("box").style.top = pos + "px";
setTimeout(moveBox, 25) //sped up for convenience
}
moveBox();
}
move();
#box {
position: absolute;
height: 1em;
width: 1em;
background-color: black;
}
<div id="box" style="bottom: 318px"></div>