获取鼠标滚轮JQuery事件处理程序的指导

3

我想通过绑定一个mousewheel事件来确定用户“滚动鼠标”的方向。

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

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。

2个回答

5

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

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

我已经更新了您的 jsfiddle,使用了这段代码。

另外,请注意,mousewheel 事件已经被弃用,您应该使用 wheel 事件。


.mousewheel更改为.wheel后,警报框始终返回down,即使向上滚动也是如此。 - undefined
@TimLewis 我在这个更新的 jsfiddle 中没有看到这种行为。https://jsfiddle.net/qexb1207/2/ - undefined
嗯...你用的是什么浏览器?我注意到在Firefox中只有down,但Chrome显示了正确的方向。 - undefined

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

看这个: 如何在jQuery中获取鼠标滚轮事件?

1
@AlanBuchanan 你是对的,它不需要。我会编辑的。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接