Detect/measure scroll speed

后端 未结 3 1488
广开言路
广开言路 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:12

    This is a simple script to give you an idea
    when you start scrolling a timer increase count var.

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    <style>
    body{height:2000px;}
    #get{position:fixed;top:0px;}
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        var timer = null;
        var count=0
        $(window).on('scroll', function() {
            if(timer !== null) {
                clearTimeout(timer); 
            }
            function increase(){
                 count++
                 timer = setTimeout(increase,50)
                }
            increase()
         });
        $('#get').click(function(){
            alert(count)
            count=0
            })
    })
    </script>
    </head>
    <body>
    <input name="" type="button" id="get" value="getTime">
    <body>
    </html>
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-23 22:28

    Here is a script I just custom made for your issue. JS Bin

    You can view the speed of scroll in the console log. It gives negative values for scrolling up and positive for scrolling down. The actual placement of the scroll bar is constantly updated in the scroll window for more information to glean. This should get you going in the right direction.

    0 讨论(0)
提交回复
热议问题