【发布时间】:2019-01-19 05:36:43
【问题描述】:
我正在尝试使用 requestanimationframe 使对象跳转。 finalposition 变量保存对象应出现在页面底部上方的像素数。
根据我的代码,对象应该平滑地移动到最大高度,然后平滑地向下移动两个事件,耗时=500ms ..但是当我运行代码时,对象立即出现在最大高度,然后在 500ms 内平滑地向下移动...我如何让这两个事件在 500 毫秒内顺利进行?
let time = {
start: null,
total: 500
};
const moveup = now => {
if (!time.start) time.start = now;
time.elapsed = now - time.start;
let progress = time.elapsed / time.total;
let position = progress * finalPosition;
obj.style.bottom = position + 'px';
if (progress < 1) requestAnimationFrame(moveup);
};
const movedown = now => {
if (!time.start) time.start = now;
time.elapsed = now - time.start;
let progress = time.elapsed / time.total;
let position = finalPosition*(1-progress);
obj.style.bottom = position + 'px';
if (progress < 1) requestAnimationFrame(movedown);
};
function jump(){
requestAnimationFrame(moveup);
time.start=0;
requestAnimationFrame(movedown);
}
document.addEventListener('keydown',jump,false)
【问题讨论】:
标签: javascript addeventlistener requestanimationframe