如何禁用/启用页面滚动

时间:2019-04-16 07:30:54

标签: javascript google-chrome browser scroll

我正在尝试编写一个禁用/启用页面滚动的JS代码。 Chrome显然存在问题-控制台显示此错误

Unable to preventDefault inside passive event listener due to target being treated as passive.

这是我的JS代码:

var keys = [32,33,34,35,36,37,38,39,40];

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;  
}

function keydown(e) {
    for (var i = keys.length; i--;) {
        if (e.keyCode === keys[i]) {
            preventDefault(e);
            return;
        }
    }
}

function wheel(e) {
  preventDefault(e);
}

function disable_scroll() {
  if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', wheel, false);
  }
  window.onmousewheel = document.onmousewheel = wheel;
  document.onkeydown = keydown;
  disable_scroll_mobile();
}

function enable_scroll() {
    if (window.removeEventListener) {
        window.removeEventListener('DOMMouseScroll', wheel, false);
    }
    window.onmousewheel = document.onmousewheel = document.onkeydown = null;  
    enable_scroll_mobile();
}

// MOBILE
function disable_scroll_mobile(){
  document.addEventListener('touchmove',preventDefault, false);
}
function enable_scroll_mobile(){
  document.removeEventListener('touchmove',preventDefault, false);
}

我尝试使用此小技巧↓解决它。我在{ passive: false }中添加了eventListener,但这无济于事:

function disable_scroll() {
      if (window.addEventListener) {
          window.addEventListener('DOMMouseScroll', wheel, { passive: false });
      }
      window.onmousewheel = document.onmousewheel = wheel;
      document.onkeydown = keydown;
      disable_scroll_mobile();
    }

    function enable_scroll() {
        if (window.removeEventListener) {
            window.removeEventListener('DOMMouseScroll', wheel, { passive: false });
        }
        window.onmousewheel = document.onmousewheel = document.onkeydown = null;  
        enable_scroll_mobile();
    }

代码笔位于https://codepen.io/wesleypimentel/full/KpgXJW,用于测试

1 个答案:

答案 0 :(得分:1)

在滚动时,您可以为身体提供样式

body {
  overflow-y: hidden;
  }

或普通js

document.body.style.overflow = 'hidden';

在函数调用上