简体   繁体   中英

How to disable/enable page scroll

I am trying to write a JS code that disables/enables page scroll. Apparently there is an issue within Chrome - the console shows this error

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

Here is my JS code:

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);
}

I tried to solve it using this little fix ↓. I added { passive: false } into the eventListener s but it will not help:

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();
    }

The codepen is here https://codepen.io/wesleypimentel/full/KpgXJW for testing purposes

on scroll you could provide a style to body as

body {
  overflow-y: hidden;
  }

or in plain js

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

on a function call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM