使用JS / jQuery禁用窗口垂直滚动的跨浏览器方法

时间:2011-11-29 12:49:21

标签: javascript jquery

我需要在mouseover特定div时禁用窗口滚动,并在mouseout上启用它。但是有必要保留滚动条,因此overflow: hidden无济于事。

我写了一些JS,但这是在IE9和Opera中的错误。

var win_scrolltop, is_mydiv_mouseovered = false;
$('#mydiv').hover(
    function(){
        win_scrolltop = $(window).scrollTop();
        is_mydiv_mouseovered = true;
    },
    function() {
        is_mydiv_mouseovered = false;
    }
)
$(window).scroll(function() {
    if (is_mydiv_mouseovered) $(window).scrollTop(win_scrolltop);
});

1 个答案:

答案 0 :(得分:0)

我找到this回答,摆弄了一点,结果就是这样:

var scrollThing = {
    // 33: PageUp, 34: PageDown, 35: End, 36: Home, 37: Left, 38: Up, 39: Right, 40: Down
    keys: [33, 34, 35, 36, 37, 38, 39, 40],
    preventDefault: function(e) {
        e = e || window.event;
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.returnValue = false;
    },
    keydown: function(e) {
        for (var i = scrollThing.keys.length; i--;) {
            if (e.keyCode === scrollThing.keys[i]) {
                scrollThing.preventDefault(e);
                return;
            }
        }
    },
    disable: function() {
        if (window.addEventListener) {
            window.addEventListener('DOMMouseScroll', scrollThing.preventDefault, false);
        }
        window.onmousewheel = document.onmousewheel = scrollThing.preventDefault;
        document.onkeydown = scrollThing.keydown;
    },
    enable: function() {
        if (window.removeEventListener) {
            window.removeEventListener('DOMMouseScroll', scrollThing.preventDefault, false);
        }
        window.onmousewheel = document.onmousewheel = document.onkeydown = null;
    }
}
$('#mydiv').hover(scrollThing.disable, scrollThing.enable);

工作example