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

问题描述:移动端当有fixed遮罩背景和弹出层时,在屏幕上滑动能够滑动背景下面的内容,就是所谓的滚动穿透问题。

解决方案:

body.modal-open{

position:fixed;

width:100%;

}

如果只用上面的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

*/

varModalHelper = (function(bodyCls){

varscrollTop;

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);

document.body.removeAttribute("style");

// scrollTop lost after set position:fixed, restore it back.

document.scrollingElement.scrollTop = scrollTop;

}

};

})('modal-open');

弹层显示时调用 ModalHelper.afterOpen();

弹层隐藏时调用 ModalHelper.beforeClose();

至此滚动穿透就解决了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容