Prevent mouse wheel scrolling, but not scrollbar e

2019-02-10 05:41发布

问题:

I need to make a webpage scrollable only by scrolling bar. I have tried to find how to catch scroll bar event, but as i see it is impossible. Currently i use this functions:

function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;
    }
}
function wheel(e) {
    preventDefault(e);
}
function disable_scroll() {
    if (window.addEventListener) {
        window.addEventListener('DOMMouseScroll', wheel, false);
    }
    window.onmousewheel = document.onmousewheel = wheel;
}

But they are not very useful in my situation, because they block all scroll events. Do you have any ideas? I am thinking about it 3 days already and i didn't find any answer (and questions also). Thanks!

回答1:

You can try this;

window.onwheel = function(){ return false; }

This will prevent window scrolling with mouse wheel. If a content of <div> or other element is scrollable you can prevent it too like this;

document.getElementById('{element-id}').onwheel = function(){ return false; }

Cheers...



回答2:

jQuery solution to prevent window scrolling with mouse wheel:

$(window).bind('mousewheel DOMMouseScroll', function(event){ return false});

If you want to prevent scrolling with mouse wheel in a single DOM element, try this:

$('#{element-id}').bind('mousewheel DOMMouseScroll', function (e) { return false; });

The DOMMouseScroll event is used in Firefox, so you have to listen on both.



回答3:

I'm currently using this and it works fine. Scrolling using the bar works fine, but mouse wheel won't work.

The reason i'm doing it this way is that I have custom code to scroll the way I want, but if don't add any code it will just don't scroll on wheel.

window.addEventListener('wheel', function(e) {  
    e.preventDefault();
    // add custom scroll code if you want
}