这是working demo。使用纯 JavaScript 可以做到这一点:
const { body, documentElement } = document;
let { scrollTop } = document.documentElement;
function disableScroll() {
scrollTop = documentElement.scrollTop;
body.style.top = `-${scrollTop}px`;
body.classList.add("scroll-disabled");
}
function enableScroll() {
body.classList.remove("scroll-disabled");
documentElement.scrollTop = scrollTop;
body.style.removeProperty("top");
}
这是 CSS:
.scroll-disabled {
position: fixed;
width: 100%;
overflow-y: scroll;
}
我们在body 上使用position: fixed 来防止它被滚动,我们使用overflow-y 来显示滚动条。由于position: fixed 的工作方式,我们还需要设置width。
我们跟踪滚动位置并在禁用滚动时更新它,以便我们可以在禁用滚动时使用top 适当地定位body,并在启用滚动时恢复滚动位置。否则body 在禁用或启用滚动时会一直跳到顶部。
启用滚动时,我们会从 body 中删除 top 样式。如果您在 body 上的 position 与 static 不同,这可以防止它破坏您的布局。
如果你在html上使用scroll-behavior: smooth,你还需要像这样修改enableScroll函数:
function enableScroll() {
body.classList.remove("scroll-disabled");
// Set "scroll-behavior" to "auto"
documentElement.style.scrollBehavior = "auto";
documentElement.scrollTop = scrollTop;
// Remove "scroll-behavior: auto" after restoring scroll position
documentElement.style.removeProperty("scroll-behavior");
body.style.removeProperty("top");
}
我们需要将scroll-behavior临时设置为auto,这样就不会跳转了。