# 移动端滚动穿透问题解决方案

*Published:* 2023-07-27
*Author:* 客服001

#### 温馨提醒

如果文章内容或图片资源失效，请留言反馈，我们会及时处理，谢谢

本文最后更新于2023年7月27日，已超过 180天没有更新



移动端当有 fixed 遮罩背景和弹出层时，在屏幕上滑动能够滑动背景下面的内容，这就是著名的滚动穿透问题

解决方案 position: fixed

如果只是上面的 css，滚动条的位置同样会丢失，所以如果需要保持滚动条的位置需要用 js 保存滚动条位置关闭的时候还原滚动位置。

```
/**
  * ModalHelper helpers resolve the modal scrolling issue on mobile devices
  * https://github.com/twbs/bootstrap/issues/15852
  * requires document.scrollingElement polyfill https://github.com/yangg/scrolling-element
  */
var ModalHelper = (function(bodyCls) {
  var scrollTop;
  return {
    afterOpen: function() {
      scrollTop = document.scrollingElement.scrollTop;
      document.body.classList.add(bodyCls);
      document.body.style.top = -scrollTop + 'px';
    },
    beforeClose: function() {
      document.body.classList.remove(bodyCls);
      // scrollTop lost after set position:fixed, restore it back.
      document.scrollingElement.scrollTop = scrollTop;
    }
  };
})('modal-open');
```

调用

```
//弹框出现时
ModalHelper.afterOpen();

//弹框隐藏时
ModalHelper.beforeClose();
```