移动端滚动穿透

背景

滚动穿透问题:移动端当有fixed 遮罩背景和弹出层时,在屏幕上滑动能够滑动背景下面的内容。

解决方案

一 设置body,html样式overflow hidden

1
2
3
4
body {
overflow: hidden;
height: 100%;
}

禁用 html 和 body 的滚动条,有时还需设置html同样样式控制页面滚动,此方案使用绝大部分PC使用场景(长页面弹窗时需要记录滚动位置,窗口关闭还原到原来位置),但移动端效果无效。

二 modal设置touchmove事件preventDefault

1
2
3
4
5
6
modal.addEventListener('touchmove', function(e) {
e.preventDefault();
}, {
passive:false, // 是否永远不会调用 preventDefault()
capture:true, // 是否捕获冒泡
});

此方案可阻止页面滚动,但弹窗如果有滚动内容,就会被阻止,无法滚动。

三 设置body样式position: fixed

1
2
3
4
body.noscroll {
position: fixed;
width: 100%;
}

js控制body样式,弹窗设置position:fixed,关闭弹窗还原

1
2
3
4
5
6
7
8
9
10
11
const bodyEl = document.body;
let scrollTop = 0;
if (showModal) {
scrollTop = window.scrollY || 0; // 记录滚动位置
bodyEl.style.position = 'fixed';
bodyEl.style.top = -scrollTop + 'px';
} else {
bodyEl.style.position = '';
bodyEl.style.top = '';
window.scrollTo(0, scrollTop); // 回到原先的top
}

此方案完美解决滚动穿透问题,推荐使用此方案。

您的支持将鼓励我继续创作!