Use jQuery to check mousewheel event without scrollbar

空扰寡人 提交于 2020-01-09 04:58:05

问题


How to check mousewheel movement without scrollbar?

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

回答1:


I highly recommend you use this jQuery plugin: PLUGIN

Without a plugin, try this example: EXAMPLE

HTML:

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

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.




回答2:


use this code

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



回答3:


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

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/




回答4:


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

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

You can also use deltaX to see horizontal scroll, or deltaZ if you've got some crazy 3D thing going on.



来源:https://stackoverflow.com/questions/18880159/use-jquery-to-check-mousewheel-event-without-scrollbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!