我的测试代码在这里http://jsfiddle.net/jDck9/请点击运行进行测试,请使用webkit浏览器打开它。
简单地说,我想在给定时间内移动一个盒子,这很简单。但我的例子有问题,也许是inaccuracy of JS timer
,我的例子效果不好。
它要么在到达目标位置之前从停止动画的目标位置稍微移动一点。
我正在寻找解决这个问题的解决方案,任何有任何想法的人?
答案 0 :(得分:2)
这是新代码:
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);
}
答案 1 :(得分:0)
您从未将newLeft分配给existingLeft。
这个有效:
var target = document.querySelector('.box');
var duration = 1000; // 1 second
var existingLeft = 0;
var targetLeft = 300;
function animate() {
var step = function () {
var elapsed = parseFloat(Date.now() - startTime, 10) / duration;
var newLeft = Math.round(existingLeft + (targetLeft - existingLeft) * elapsed);
target.style.left = newLeft + 'px';
existingLeft = newLeft;
if(elapsed >=1) {
// stop
} else {
requestAnimationFrame(step);
}
}
step();
}
var startTime = Date.now();
animate();