我的测试代码在这里http://jsfiddle.net/jDck9/请点击运行测试一下,并使用webkit浏览器打开。
简单来说,我想在给定的时间内移动一个盒子,就这么简单。但是我的例子有问题,可能是JS定时器不准确
,我的例子不能很好地工作。
在到达目标位置之前,它要么从停止动画的目标位置移动得更远一些。
我正在寻找解决此问题的解决方案,有人有任何想法吗?
最佳答案
- 步骤回调中有时间戳参数,表示时间。
- 由于 elapsed 是 float,所以很难让 newLeft 与 targetLeft 完全相同,所以只需在最后一步赋值 targetLeft 即可。
这是新代码:
function animate() {
var start = null, progress;
function step(timestamp) {
if (start == null)
start = timestamp;
//here we know how many mill-secs passed
progress = timestamp - start;
var elapsed = progress / duration;
if (elapsed >= 1) {
//well, time is up, just give "left" the right value
target.style.left = targetLeft + 'px';
} else {
var newLeft = existingLeft + (targetLeft - existingLeft) * elapsed;
//modify the left accordingly
target.style.left = newLeft + 'px';
//schedule another animation
requestAnimationFrame(step);
}
}
//let's go
requestAnimationFrame(step);
}
关于JavaScript:如何修复动画计时器的不准确问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20897555/