简体   繁体   English

在 jQuery 中获取鼠标滚轮事件?

[英]Get mouse wheel events in jQuery?

有没有办法在 jQuery 中获取鼠标滚轮事件(不是谈论scroll事件)?

​$(document).ready(function(){
    $('#foo').bind('mousewheel', function(e){
        if(e.originalEvent.wheelDelta /120 > 0) {
            console.log('scrolling up !');
        }
        else{
            console.log('scrolling down !');
        }
    });
});

Binding to both mousewheel and DOMMouseScroll ended up working really well for me:结合这两个mousewheelDOMMouseScroll结束了工作对我很好:

$(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.此方法适用于 IE9+、Chrome 33 和 Firefox 27。


Edit - Mar 2016编辑 - 2016 年 3 月

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.滚动事件的 MDN 页面有一个很好的方法来检索滚动位置,它使用requestAnimationFrame ,这比我以前的检测方法更可取。 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 . 请参阅CodePen上 Jesse Dupuy ( @blindside85 ) 的 Pen Vanilla JS 滚动跟踪

This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+此代码目前适用于Chrome v50, Firefox v44, Safari v9, and IE9+

References:参考:

As of now in 2017, you can just write截至 2017 年,你可以只写

$(window).on('wheel', function(event){

  // deltaY obviously records vertical scroll, deltaX and deltaZ exist too.
  // this condition makes sure it's vertical scrolling that happened
  if(event.originalEvent.deltaY !== 0){

    if(event.originalEvent.deltaY < 0){
      // wheeled up
    }
    else {
      // wheeled down
    }
  }
});

Works with current Firefox 51, Chrome 56, IE9+适用于当前的 Firefox 51、Chrome 56、IE9+

有一个插件可以检测一个区域上的上/下鼠标滚轮和速度。

Answers talking about "mousewheel" event are refering to a deprecated event.谈论“鼠标滚轮”事件的答案是指已弃用的事件。 The standard event is simply "wheel".标准事件只是“轮子”。 See https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel请参阅https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel

This worked for me:)这对我有用:)

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.originalEvent.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.originalEvent.wheelDelta < 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

from stackoverflow 来自stackoverflow

Here is a vanilla solution.这是一个香草解决方案。 Can be used in jQuery if the event passed to the function is event.originalEvent which jQuery makes available as property of the jQuery event.如果传递给函数的事件是event.originalEvent ,jQuery 将其用作 jQuery 事件的属性,则可以在 jQuery 中使用。 Or if inside the callback function under we add before first line: event = event.originalEvent;或者如果在callback函数里面我们在第一行之前添加: event = event.originalEvent; . .

This code normalizes the wheel speed/amount and is positive for what would be a forward scroll in a typical mouse, and negative in a backward mouse wheel movement.此代码规范了滚轮速度/数量,对于典型鼠标中的向前滚动是正数,而在向后鼠标滚轮移动时是负数。

Demo: http://jsfiddle.net/BXhzD/演示: http : //jsfiddle.net/BXhzD/

var wheel = document.getElementById('wheel');

function report(ammout) {
    wheel.innerHTML = 'wheel ammout: ' + ammout;
}

function callback(event) {
    var normalized;
    if (event.wheelDelta) {
        normalized = (event.wheelDelta % 120 - 0) == -0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
    } else {
        var rawAmmount = event.deltaY ? event.deltaY : event.detail;
        normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
    }
    report(normalized);
}

var event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
window.addEventListener(event, callback);

There is also a plugin for jQuery, which is more verbose in the code and some extra sugar: https://github.com/brandonaaron/jquery-mousewheel还有一个 jQuery 插件,它在代码中更加冗长,还有一些额外的糖: https : //github.com/brandonaaron/jquery-mousewheel

This is working in each IE, Firefox and Chrome's latest versions.这适用于每个 IE、Firefox 和 Chrome 的最新版本。

$(document).ready(function(){
        $('#whole').bind('DOMMouseScroll mousewheel', function(e){
            if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
                alert("up");
            }
            else{
                alert("down");
            }
        });
    });

I was stuck in this issue today and found this code is working fine for me我今天被困在这个问题上,发现这段代码对我来说很好用

$('#content').on('mousewheel', function(event) {
    //console.log(event.deltaX, event.deltaY, event.deltaFactor);
    if(event.deltaY > 0) {
      console.log('scroll up');
    } else {
      console.log('scroll down');
    }
});

use this code使用此代码

 knob.bind('mousewheel', function(e){  
 if(e.originalEvent.wheelDelta < 0) {
    moveKnob('down');
  } else {
    moveKnob('up');
 }
  return false;
});

The plugin that @DarinDimitrov posted, jquery-mousewheel , is broken with jQuery 3+ . @DarinDimitrov 发布的插件jquery-mousewheel mousewheel被 jQuery 3+ 破坏了 It would be more advisable to use jquery-wheel which works with jQuery 3+.最好使用适用于 jQuery 3+ 的jquery-wheel

If you don't want to go the jQuery route, MDN highly cautions using the mousewheel event as it's nonstandard and unsupported in many places.如果你不想走 jQuery 路线, MDN 高度警告使用mousewheel事件,因为它是非标准的并且在许多地方不受支持。 It instead says that you should use the wheel event as you get much more specificity over exactly what the values you're getting mean.相反,它说您应该使用wheel事件,因为您可以更准确地了解所获得的值的含义。 It's supported by most major browsers.大多数主要浏览器都支持它。

my combination looks like this.我的组合看起来像这样。 it fades out and fades in on each scroll down/up.它在每次向下/向上滚动时淡出和淡入。 otherwise you have to scroll up to the header, for fading the header in.否则你必须向上滚动到标题,以淡入标题。

var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
    if(e.originalEvent.wheelDelta > 0) {
        if (header.data('faded')) {
            header.data('faded', 0).stop(true).fadeTo(800, 1);
        }
    }
    else{
        if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
    }
});

the above one is not optimized for touch/mobile, I think this one does it better for all mobile:上面的没有针对触摸/移动优化,我认为这个对所有移动设备都更好:

var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {

    var iCurScrollPos = $(this).scrollTop();
    if (iCurScrollPos > iScrollPos) {
        if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);

    } else {
        //Scrolling Up
        if (header.data('faded')) {
            header.data('faded', 0).stop(true).fadeTo(800, 1);
        }
    }
    iScrollPos = iCurScrollPos;

});

If using mentioned jquery mousewheel plugin , then what about to use the 2nd argument of event handler function - delta :如果使用提到的jquery mousewheel 插件,那么如何使用事件处理函数的第二个参数 - delta

$('#my-element').on('mousewheel', function(event, delta) {
    if(delta > 0) {
    console.log('scroll up');
    } 
    else {
    console.log('scroll down');
    }
});

I think many key things are a bit all over the place and I needed to read all the answers to make my code work as I wanted, so I will post my findings in just one place:我认为许多关键的事情有点乱,我需要阅读所有答案才能让我的代码按我想要的方式工作,所以我只会在一个地方发布我的发现:

  • You should use "wheel" event over the other deprecated or browser specific events.您应该在其他已弃用或浏览器特定事件上使用"wheel"事件。
  • Many people here is getting something wrong: the opposite of x>0 is x<=0 and the opposite of x<0 is x>=0 , many of the answers in here will trigger scrolling down or up incorrectly when x=0 (horizontal scrolling).这里许多人越来越不对劲:相反x>0就是x<=0和相反x<0就是x>=0 ,很多在这里的答案将触发滚动向下或向上不正确时, x=0 (水平滚动)。
  • Someone was asking how to put sensitivity on it, for this you can use setTimeout() with like 50 ms of delay that changes some helper flag isWaiting=false and you protect yourself with if(isWaiting) then don't do anything.有人问如何对其设置敏感度,为此,您可以使用setTimeout()和大约 50 毫秒的延迟来更改某些辅助标志isWaiting=false并使用if(isWaiting)保护自己,然后什么都不做。 When it fires you manually change isWaiting=true and just below this line you start the setTimeout again who will later change isWaiting=false after 50 ms.当它触发时,您手动更改isWaiting=true并在此行下方再次启动setTimeout ,稍后将在 50 毫秒后更改isWaiting=false

有没有一种方法可以在jQuery中获取鼠标滚轮事件(而不是scroll事件)?

I got same problem recently where $(window).mousewheel was returning undefined我最近遇到了同样的问题,其中$(window).mousewheel返回undefined

What I did was $(window).on('mousewheel', function() {});我所做的是$(window).on('mousewheel', function() {});

Further to process it I am using:进一步处理它我正在使用:

function (event) {
    var direction = null,
        key;

    if (event.type === 'mousewheel') {
        if (yourFunctionForGetMouseWheelDirection(event) > 0) {
            direction = 'up';
        } else {
            direction = 'down';
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM