Adding additional arguments to a function called back by requestAnimationFrame

断了今生、忘了曾经 提交于 2019-11-28 11:29:45

What your requestAnimationFrame statement evaluates to:

  • scroll(timestamp, distanceToScroll, secondsToScroll), where timestamp is undefined. It throws an error or returns undefined
  • window.requestAnimationFrame is executed without parameters, thus no callback

Passing an anonymous function that calls scroll with the desired parameters should do the trick:

requestAnimationFrame(function(timestamp) {
    scroll(timestamp, distanceToScroll, secondsToScroll));
});

What this evaluates to:

  • window.requestAnimationFrame is called with anonymous function as callback
  • anonymous function is called with timestamp as first parameter
  • scroll is called with current timestamp, distanceToScroll and secondsToScroll as parameters

Pure JavaScript

function scrollIntoViewSmooth(elem) {
    var move = elem.offsetTop - (elem.offsetTop - elem.parentElement.scrollTop) * 0.25;

    if (Math.abs(elem.offsetTop - move) <= 2) {
        elem.parentElement.scrollTop = elem.offsetTop;
    } else {
        elem.parentElement.scrollTop = move;
        setTimeout(scrollIntoViewSmooth, 33, elem);
    }
}

Example

scrollIntoViewSmooth(document.getElementById('stuff'));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!