參考 https://uedsky.com/2016-06/mobile-modal-scroll/ 感謝分享
案例頁面:view-source:https://uedsky.com/demo/modal-scroll.html
第一步:給body加上個css類別樣式
body.modal-open { position: fixed; width: 100%; }
第二部:創建核心函數:
/** * 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');
第三部:打開/關閉彈窗,引用核心函數
//打開彈窗 $('.D_md12 .material .addbox').on('click',function(){ $('.material_pop').addClass('show'); ModalHelper.afterOpen(); }); //關閉彈窗 // pc點擊空白區域關閉窗口 $('.popbox:not(.publish_pop)').click(function(e){ var _con = $('.popcontain'); if(!_con.is(e.target) && _con.has(e.target).length === 0){ $('.popbox').removeClass('show'); ModalHelper.beforeClose(); } }); //pc esc關閉窗口 $(document).keyup(function(event){ if(event.which=='27'){ $('.popbox.show:not(.publish_pop)').removeClass('show'); ModalHelper.beforeClose(); } }); //PC 點擊close按鈕關閉彈窗 $('.popbox:not(.publish_pop) .pop_closebtn').click(function(e){ $('.popbox').removeClass('show'); ModalHelper.beforeClose(); });
備注:
document.scrollingElement 因為瀏覽器獲取和設置 scrollTop 存在兼容性,為了簡化上面的示例,我直接使用了 document.scrollingElement 這個新標准,對於不支持的瀏覽器我寫了個 polyfill document.scrollingElement.js
檢測函數:
<script> (function() { function addScript(src, supported) { if(!supported) document.write('<script src="' + src + '" async ></' + 'script>'); } addScript('../src/polyfills/document.scrollingElement.js', document.scrollingElement); })(); </script>
document.scrollingElement.js
/** * polyfill for document.scrollingElement * https://github.com/yangg/scrolling-element */ (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 }) })()