尝试使用requestanimationframe使对象跳转的代码无效

时间:2019-01-19 05:36:43

标签: javascript addeventlistener requestanimationframe

我正在尝试使用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)

1 个答案:

答案 0 :(得分:1)

这里有几个问题。

除非您的代码不完整,否则您在代码中的任何地方都没有finalPosition。

更重要的是,跳转功能没有正确地等待事件,整个功能一次运行,也就是说,它不等待上移再运行下移,而是同时运行。

大概您只观察movedown的原因是这两者都发生在每一帧上,但是movedown却发生在上移之后。

屁股,您将能够看出下面的代码片段,我在这里所做的是重新排列了一些现有代码。我已将第一个movedown调用移至moveup循环的末尾,并在movedown末尾重新设置了时间。

let finalPosition = 100;
let time = {
  start: null,
  total: 500,
};

let obj = document.querySelector('.foo');
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);
  } else {
    time.start = 0;
    requestAnimationFrame(movedown);
  }
};

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);
  } else {
    time.start = 0;
  }
};       

function jump() {
  requestAnimationFrame(moveup);
}

document.addEventListener('keydown', jump, false);
.foo {
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%) translateY(-50%);
}

.frame {
  height: 150px;
  width: 150px;
  position: absolute;
  top: 50%;
  right: 50%;
  transform: translateX(50%) translateY(-50%);
  background-color: #cdb;
}
<div class="frame">
  <div class="foo"></div>  
</div>
<button onclick="jump()">jump</button>