我有一个模式,当我点击时,我的身体会变成overflow:hidden。这将移除滚动条,这样我的页面就不会滚动。当您关闭模式时,我的身体会切换回overflow:auto,页面可以再次滚动。这是通过我在Javascript中设置的两个简单函数完成的。
function hidden() {
document.querySelector("body").style.overflow = "hidden";
}
function show() {
document.querySelector("body").style.overflow = "auto";
}但是,当滚动条被移除时,您可以看到我的整个页面向右移动。有什么办法可以让我把这件事做得不太糟吗?或者,当模式结束时,可能有一种不同的方式来禁用滚动?
发布于 2022-08-05 18:58:03
您可以禁用滚动,同时将滚动条保留在JS事件侦听器中,以拦截如下所示的滚动事件:
const ignoreScroll = (e) => {
e.preventDefault();
};
// Add scrolling block
document.addEventListener('scroll', ignoreScroll);
document.addEventListener('mousewheel', ignoreScroll);
document.addEventListener('touchmove', ignoreScroll);
// Remove scrolling block
document.removeEventListener('scroll', ignoreScroll);
document.removeEventListener('mousewheel', ignoreScroll);
document.removeEventListener('touchmove', ignoreScroll);还可以以编程方式应用touch-action: none CSS规则来禁用元素上的滚动。
https://stackoverflow.com/questions/73254118
复制相似问题