In web development, there are times when we need to control whether a page can scroll. This article will introduce two common methods to disable and allow page scrolling, namely, directly manipulating the page style and blocking the default behavior through event listeners.

Method 1: Directly operate the page style

Forbid page scrolling:

复制代码document.body.style.overflow = 'hidden';

Allow the page to scroll.

复制代码document.body.style.overflow = 'visible';

This method controls scrolling by directly modifying the style of the pageoverflow属性设置为hidden可以禁止页面滚动,设置为visible可以允许页面滚动。

Method 2: Block default behavior through event listeners

复制代码// 禁止页面滚动function disableScroll() {  document.body.addEventListener('touchmove', preventDefault, { passive: false });}// 允许页面滚动function enableScroll() {  document.body.removeEventListener('touchmove', preventDefault, { passive: false });}// 阻止touchmove事件的默认行为function preventDefault(event) {  event.preventDefault();}

This method prevents event listeners by adding or removing themtouchmove事件的默认行为,从而禁止或允许页面滚动。在需要禁止页面滚动的时候,调用disableScroll()函数;在需要允许页面滚动的时候,调用enableScroll()函数。

sample code

Here is an example code that demonstrates how to disable page scrolling when clicking Show Mask Layer and disable page scrolling when closing Mask Layer:

复制代码var maskElement = document.getElementById('mask'); // 假设遮罩层的元素id为 "mask"// 点击显示遮罩层function showMask() {  maskElement.style.display = 'block';  disableScroll(); // 禁止页面滚动}// 点击关闭遮罩层function closeMask() {  maskElement.style.display = 'none';  enableScroll(); // 解除页面禁止滚动}

In the above code, when you click Show Mask Layer, you calldisableScroll()函数来禁止页面滚动;当点击关闭遮罩层时,调用enableScroll()函数来解除页面禁止滚动。

The above are the two common methods of disabling and allowing page scrolling. According to specific needs, you can choose the appropriate method to achieve page scrolling control.