原生javascript实现禁止浏览器滚动,滚动条不消失代码

使用css代码可以禁止网页滚动,但是会使浏览器窗口的滚动条消失。而js代码则可以让页面禁止滚动的同时,保留滚动条的显示状态,而且滚动条的位置不变。

javascript代码

var keys = { 37: 1, 38: 1, 39: 1, 40: 1 };
function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault)
        e.preventDefault();
    e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
    if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
    }
}
var oldonwheel, oldonmousewheel1, oldonmousewheel2, oldontouchmove, oldonkeydown
, isDisabled;
function disableScroll() {
    if (window.addEventListener) // older FF
        window.addEventListener('DOMMouseScroll', preventDefault, false);
    oldonwheel = window.onwheel;
    window.onwheel = preventDefault; // modern standard
    oldonmousewheel1 = window.onmousewheel;
    window.onmousewheel = preventDefault; // older browsers, IE
    oldonmousewheel2 = document.onmousewheel;
    document.onmousewheel = preventDefault; // older browsers, IE
    oldontouchmove = window.ontouchmove;
    window.ontouchmove = preventDefault; // mobile
    oldonkeydown = document.onkeydown;
    document.onkeydown = preventDefaultForScrollKeys;
    isDisabled = true;
}

function enableScroll() {
    if (!isDisabled) return;
    if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    window.onwheel = oldonwheel; // modern standard
    window.onmousewheel = oldonmousewheel1; // older browsers, IE
    document.onmousewheel = oldonmousewheel2; // older browsers, IE
    window.ontouchmove = oldontouchmove; // mobile
    document.onkeydown = oldonkeydown;
    isDisabled = false;
}
window.scrollHanlder = {
    disableScroll: disableScroll,
    enableScroll: enableScroll
};

调用代码

禁止滚动时,调用:

disableScroll()

恢复滚动时,调用函数:

enableScroll()

代码来自:https://www.zhihu.com/question/21865401#Popover19-toggle

存在的问题

会导致弹窗的滚动也禁止,需要拖动滚动条;

测试后好像不兼容Chrome浏览器。

建议使用jquery方法:jquery禁止启用滚动条滚动的代码

关键词: javascript代码