完美解决移动端H5页面的滑动穿透问题

同事的分享,记录下来。

代码如下:

css:

body.modal-open {
  position: fixed;
  width: 100%;
}

js:

// 兼容低版本 document.scrollingElement写法
      (function () {
        if (document.scrollingElement) {
          return;
        }
        var element = null;
        function scrollingElement () {
          if (element) {
            return element;
          } else if (document.body.scrollTop) {
            // speed up if scrollTop > 0
            return (element = document.body);
          }
          var iframe = document.createElement('iframe');
          iframe.style.height = '1px';
          document.documentElement.appendChild(iframe);
          var doc = iframe.contentWindow.document;
          doc.write('<!DOCTYPE html><div style="height:9999em">x</div>');
          doc.close();
          var isCompliant = doc.documentElement.scrollHeight > doc.body.scrollHeight;
          iframe.parentNode.removeChild(iframe);
          return (element = isCompliant ? document.documentElement : document.body);
        }
        Object.defineProperty(document, 'scrollingElement', {
          get: scrollingElement
        });
      })();
      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');

然后在打开遮罩层的地方添加如下js:

ModalHelper.afterOpen();

在关闭遮罩层的地方添加如下js:

ModalHelper.beforeClose();

这样,你再也不用因为页面的滑动穿透而烦恼啦~

顺便再分享一些关于滚动的优化方法:

1.消除难看的滚动条:在父元素的css添加如下代码

scrollbar-width: none;
::-webkit-scrollbar {display:none}

2.让滚动显得更加流畅:在父元素的css添加如下代码

overflow-y: scroll;
/* 增加弹性滚动,解决滚动不流畅的问题 */
-webkit-overflow-scrolling: touch;

猜你喜欢

转载自www.cnblogs.com/xinsir/p/10310663.html