js prohibits page scrolling, and the page does not shake

    Application scenario: There are multiple scroll bars in the page or there are modules that require mouse scrolling. At this time, it is necessary to disable the scrolling event of the browser, and the page does not shake.

1. Globally set the scroll bar style (scss)

Note: If you do not set the scroll bar width, you need to calculate the scroll bar width when page scrolling is disabled, otherwise it will cause the page to shake.

::-webkit-scrollbar {
  width: 7px; // 固定滚动条宽度
}
::-webkit-scrollbar-thumb {
  border-radius: 14px;
  -webkit-box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);
  background: rgba(144, 147, 153, 0.3);
}
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);
  border-radius: 0;
  background: none;
}

2. Disable page scrolling: set the page position to "fixed", fix the page at the specified height, and set the page width according to requirements.

Note: The width of the page needs to be subtracted from the width of the scroll bar, otherwise the page will shake and affect the user experience.

let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let dom = document.getElementById("app");
dom.style.position = "fixed";
dom.style.top = "-" + scrollTop + "px";
dom.style.width = "calc(100% - 7px)"; // 7px为滚动条宽度

3. Undisable page scrolling

let dom = document.getElementById("app");
let scrollTop = Math.abs(parseFloat(dom.style.top));
dom.style.position = "";
dom.style.top = "";
dom.style.width = "100%";
if (document.body) {
  document.body.scrollTop = scrollTop;
}
if (document.documentElement) {
  document.documentElement.scrollTop = scrollTop;
}

Guess you like

Origin blog.csdn.net/weixin_46653941/article/details/126886583