获取鼠标滚轮 JQuery 事件处理程序的方向

Get direction for mousewheel JQuery event handler

我试图通过对元素的 mousewheel 事件进行绑定来确定用户 "mousewheeled" 的方向。

您可以在下面的代码片段中看到,当将鼠标滚到灰色矩形上时,会触发该事件。

JSFiddle

HTML

<div class="rect"></div>
<div>
    Mousewheel event state : 
    <label class="event-state-mousewheel">Triggered !</label>
</div>

CSS

.rect {
    width : 200px;
    height : 200px;
    background-color : lightgrey;
}

.event-state-mousewheel {
    color : red;
    display : none;
}

JavaScript

$(function() {
    $('.rect').on('mousewheel', function(event) {
        $(".event-state-mousewheel").stop(true, false).fadeIn(250).fadeOut(250);
    });
});

问题

我找不到获取方向的方法。我尝试调试事件触发时返回的对象,但它太大而无法调试,因为其中的元素数量巨大。

问题

是否有使用这些元素(从返回的对象)获取鼠标滚轮方向的公式? 或者是否有类似 $("#element").on("mousewheeltop") 的事件?

注意

我希望尽可能不使用任何其他外部插件,只希望 JQuery。

属性wheelDelta和detail是你需要的,如下:

if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
    // Scroll up
}
else {
    // Scroll down
}

我已经使用此代码更新了您的 jsfiddle

另外,请注意 mousewheel 事件是 deprecated,您应该改用 wheel

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

观看此视频:Get mouse wheel events in jQuery?