同事的分享,記錄下來。css
代碼以下:html
css:web
body.modal-open { position: fixed; width: 100%; }
js:app
// 兼容低版本 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:spa
ModalHelper.beforeClose();
這樣,你不再用由於頁面的滑動穿透而煩惱啦~rest
順便再分享一些關於滾動的優化方法:code
1.消除難看的滾動條:在父元素的css添加以下代碼htm
scrollbar-width: none; ::-webkit-scrollbar {display:none}
2.讓滾動顯得更加流暢:在父元素的css添加以下代碼blog
overflow-y: scroll; /* 增長彈性滾動,解決滾動不流暢的問題 */ -webkit-overflow-scrolling: touch;