jQuery 使用jQuery在没有滚动条的情况下检查鼠标滚轮事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18880159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:41:10  来源:igfitidea点击:

Use jQuery to check mousewheel event without scrollbar

jqueryscrollscrollbarmousewheel

提问by saik0o

How to check mousewheel movement without scrollbar?

如何在没有滚动条的情况下检查鼠标滚轮的移动?

$(document).mousewheel(function() {
     clicker.html("a7a");
});

回答by Aaron

I highly recommend you use this jQuery plugin: PLUGIN

我强烈推荐你使用这个 jQuery 插件:PLUGIN

Without a plugin, try this example: EXAMPLE

没有插件,试试这个例子:EXAMPLE

HTML:

HTML:

<div id='foo' style='height:300px; width:300px; background-color:red'></div>

Javascript:

Javascript:

$('#foo').bind('mousewheel', function(e) {
    if(e.originalEvent.wheelDelta / 120 > 0) {
        alert('up');
    } else {
        alert('down');
    }
});

There is no scrollbar on the div but the wheel event is detected.

div 上没有滚动条,但检测到滚轮事件。

回答by Behnam Mohammadi

use this code

使用此代码

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

回答by Alvaro

And, if you don't want to use any plugin at all (IE8, Chrome, Firefox, Safari, Opera...), just do this:

而且,如果您根本不想使用任何插件(IE8、Chrome、Firefox、Safari、Opera...),请执行以下操作:

if (document.addEventListener) {
    document.addEventListener("mousewheel", MouseWheelHandler(), false);
    document.addEventListener("DOMMouseScroll", MouseWheelHandler(), false);
} else {
    sq.attachEvent("onmousewheel", MouseWheelHandler());
}


function MouseWheelHandler() {
    return function (e) {
        // cross-browser wheel delta
        var e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));

        //scrolling down?
        if (delta < 0) {
            alert("Down");
        }

        //scrolling up?
        else {
             alert("Up");
        }
        return false;
    }
}

Living example: http://jsfiddle.net/CvCc6/1/

活生生的例子:http: //jsfiddle.net/CvCc6/1/

回答by nHaskins

This is just an update to @Aaron's answer, using the new "wheel" event, described here: https://developer.mozilla.org/en-US/docs/Web/Events/wheel

这只是对@Aaron 的回答的更新,使用新的“wheel”事件,描述如下:https: //developer.mozilla.org/en-US/docs/Web/Events/wheel

$('#foo').on('wheel', function(e){
    if(e.originalEvent.deltaY < 0) {
        console.log('scrolling up !');
    } else{
        console.log('scrolling down !');
    }
});

You can also use deltaXto see horizontal scroll, or deltaZif you've got some crazy 3D thing going on.

您还可以使用deltaX查看水平滚动,或者deltaZ如果您有一些疯狂的 3D 事情发生。