Detect/measure scroll speed

后端 未结 3 1490
广开言路
广开言路 2020-12-23 21:46

I\'m trying to think of a way to measure the velocity of a scroll event, that would produce some sort of a number which will represent the speed (d

3条回答
  •  时光取名叫无心
    2020-12-23 22:16

    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() );
    };
    

    Demo page: http://codepen.io/vsync/pen/taAGd/

    Simplified demo: http://jsbin.com/mapafadako/edit?js,console,output


    For real fun, give a real website these rules, then copy the JS and run it

提交回复
热议问题