参考 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
})
})()