如何在不影响样式的情况下阻止页面滚动?

How to block the page scrolling without affecting the style?

我想阻止页面滚动但不更改我的页面样式(例如使用 overflow: hidden;)。

我试过用这个:

$('body').on('scroll mousewheel touchmove', function(e) {
    e.preventDefault()
    e.stopPropagation()
    return false
});

但是滚动没有被阻止,我收到了这个控制台错误:

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See <URL>

有什么解决办法吗?

有。

$('body').on('scroll mousewheel touchmove', function(e) {
  // Get the current page scroll position 
  let scrollTop =  
    window.pageYOffset || document.documentElement.scrollTop; 
  let scrollLeft =  
    window.pageXOffset || document.documentElement.scrollLeft, 

    // if any scroll is attempted, 
    // set this to the previous value 
    window.onscroll = function() { 
    window.scrollTo(scrollLeft, scrollTop); 
  }; 
});

我找到了禁用滚动的正确方法:

function preventScroll(e) {
   e.preventDefault()
}

document.addEventListener('wheel', preventScroll, { passive: false })

为了再次允许:

document.removeEventListener('wheel', preventScroll, { passive: false })