使用requestAnimationFrame

时间:2016-11-18 18:07:08

标签: javascript requestanimationframe

我使用这个函数来设置某些元素的转换属性,但是在firefox中动画并不是那么流畅,当窗口大小较大时(在任何浏览器中)它都不太流畅。我有在博客上阅读了很多东西,说我可以使用requestAnimationFrame制作更流畅的动画,但我不知道如何在我的函数中实现它。可以有人解释我如何使用它在我的功能里面?

function sectionMovement(delay,section) {
  setTimeout(function () {
    var val = ((v.sectionIndex + 1) > v.leavingSection) ?
      val = 100 : 
      val = 0;
    document.getElementById("sec_"+section+"").style.transform = "translateY(-"+val+"%)"
  }, delay);
};

1 个答案:

答案 0 :(得分:0)

这样的事情:

function updateSection(selector) {
  var elem = document.getElementById("sec_" + section);
  return function step() {
    var val = ((v.sectionIndex + 1) > v.leavingSection) ? // not sure what 'v' is?
      100 : 
      0;

    elem.style.transform = "translateY(-"+val+"%)";
    requestAnimationFrame(step);
  }
}

var sel = "myElementId";
requestAnimationFrame(updateSection(sel));

您还可能需要检查外部变量以了解何时停止动画。