Get mouse wheel events in jQuery?

前端 未结 14 1233
旧巷少年郎
旧巷少年郎 2020-11-22 13:26

Is there a way to get the mouse wheel events (not talking about scroll events) in jQuery?

14条回答
  •  失恋的感觉
    2020-11-22 13:35

    Binding to both mousewheel and DOMMouseScroll ended up working really well for me:

    $(window).bind('mousewheel DOMMouseScroll', function(event){
        if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
            // scroll up
        }
        else {
            // scroll down
        }
    });
    

    This method is working in IE9+, Chrome 33, and Firefox 27.


    Edit - Mar 2016

    I decided to revisit this issue since it's been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame, which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:

    (function() {
      var supportOffset = window.pageYOffset !== undefined,
        lastKnownPos = 0,
        ticking = false,
        scrollDir,
        currYPos;
    
      function doSomething(scrollPos, scrollDir) {
        // Your code goes here...
        console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);
      }
    
      window.addEventListener('wheel', function(e) {
        currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;
        scrollDir = lastKnownPos > currYPos ? 'up' : 'down';
        lastKnownPos = currYPos;
    
        if (!ticking) {
          window.requestAnimationFrame(function() {
            doSomething(lastKnownPos, scrollDir);
            ticking = false;
          });
        }
        ticking = true;
      });
    })();

    See the Pen Vanilla JS Scroll Tracking by Jesse Dupuy (@blindside85) on CodePen.

    This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+

    References:

    • https://developer.mozilla.org/en-US/docs/Web/Events/scroll
    • https://developer.mozilla.org/en-US/docs/Web/Events/wheel

提交回复
热议问题