检测/测量滚动速度

vsy*_*ync 19 javascript events scroll

我试图想出一种方法来测量滚动事件的速度,这将产生某种数字,它将代表速度(从滚动点A到B点的距离相对于它所花费的时间).


我欢迎任何伪代码形式的建议......我试图在网上找到有关这个问题的信息,但找不到任何东西.自2014年以来非常奇怪,谷歌怎么可能没有这个...奇怪!

vsy*_*ync 28

var checkScrollSpeed = (function(settings){
    settings = settings || {};

    var lastPos, newPos, timer, delta, 
        delay = settings.delay || 50; // in "ms" (higher means lower fidelity )

    function clear() {
      lastPos = null;
      delta = 0;
    }

    clear();

    return function(){
      newPos = window.scrollY;
      if ( lastPos != null ){ // && newPos < maxScroll 
        delta = newPos -  lastPos;
      }
      lastPos = newPos;
      clearTimeout(timer);
      timer = setTimeout(clear, delay);
      return delta;
    };
})();

// listen to "scroll" event
window.onscroll = function(){
  console.log( checkScrollSpeed() );
};
Run Code Online (Sandbox Code Playgroud)

演示页面:http: //codepen.io/vsync/pen/taAGd/

简化演示:http: //jsbin.com/mapafadako/edit?js,console,output


为了真正的乐趣,给这个规则一个真实的网站,然后复制JS并运行它