美文网首页
移动端滚动穿透问题解决方案

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

作者: AmilyHao | 来源:发表于2017-05-02 16:27 被阅读0次

问题描述:移动端当有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();

至此滚动穿透就解决了。

相关文章

网友评论

      本文标题:移动端滚动穿透问题解决方案

      本文链接:https://www.haomeiwen.com/subject/cxactxtx.html