移动端滚动穿透问题完美解决方案
来源:互联网 发布:诸葛亮 司马懿 知乎 编辑:程序博客网 时间:2024/06/05 04:02
移动端滚动穿透问题完美解决方案ion: fixed
问题
众所周知,移动端当有 fixed 遮罩背景和弹出层时,在屏幕上滑动能够滑动背景下面的内容,这就是臭名昭著的滚动穿透问题
之前搜索了一圈,找到下面两种方案
css 之 overflow: hidden
SCSS
.modal-open {&, body {overflow: hidden;height: 100%;}}
页面弹出层上将 .modal-open
添加到 html 上,禁用 html 和 body 的滚动条
但是这个方案有两个缺点:
- 由于 html 和 body的滚动条都被禁用,弹出层后页面的滚动位置会丢失,需要用 js 来还原
- 页面的背景还是能够有滚的动的效果
js 之 touchmove + preventDefault
JavaScript
modal.addEventListener('touchmove', function(e) {e.preventDefault();}, false);
这样用 js 阻止滚动后看起来效果不错了,但是也有一个缺点:
- 弹出层里不能有其它需要滚动的内容(如大段文字需要固定高度,显示滚动条也会被阻止)
上面两个方案都有缺点,今天用英文关键字 google 了一下,才发现原来还有更好的方案
解决方案 position: fixed
CSS
body.modal-open {position: fixed;width: 100%;}
如果只是上面的 css,滚动条的位置同样会丢失
所以如果需要保持滚动条的位置需要用 js 保存滚动条位置关闭的时候还原滚动位置
JavaScript
/*** 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');
这样上面3个缺点都解决了,至此滚动穿透就完美解决了
完整的示例
document.scrollingElement
因为浏览器获取和设置 scrollTop 存在兼容性,为了简化上面的示例,我直接使用了 document.scrollingElement 这个新标准,对于不支持的浏览器我写了个 polyfill document.scrollingElement.js
参考
- https://github.com/twbs/bootstrap/issues/15852
- https://imququ.com/post/document-scrollingelement-in-chrome.html
- https://github.com/mathiasbynens/document.scrollingElement
- https://segmentfault.com/q/1010000002942948
原文地址:https://uedsky.com/2016-06/mobile-modal-scroll/
获取最佳阅读体验并参与讨论,请访问原文
阅读全文
0 0
- 移动端滚动穿透问题完美解决方案
- 移动端滚动穿透解决方案
- 移动端 滚动穿透问题
- 移动页面滚动穿透解决方案(荐)
- 解决移动端可恨的滚动穿透问题
- 移动端滚动穿透的问题解决
- 解决移动端页面滑动穿透问题
- 移动端页面touch会"穿透"的解决方案
- 定位filed穿透滚动问题
- 移动端弹出层弹出 body还能滚动(滚动穿透)
- 移动端 ios键盘挡住底部 输入框的问题完美解决方案
- 移动页面【点击穿透】问题
- 移动端300ms点击延迟和点击穿透问题
- 移动端滚动条的问题之一
- 移动端滚动的橡皮筋问题
- 移动端滚动的橡皮筋问题
- 手机移动端可滚动的导航代码--css解决方案
- JBulder中文问题完美解决方案
- 15. 机器学习基石
- Spring boot 入门程序详解
- struts2简介
- 获取iframe中的内容、查找获取指定元素(关于用c++调用WEBBROWSER控件,使用相关接口操作web页面元素的一些方法)
- RecyclerView增 删
- 移动端滚动穿透问题完美解决方案
- oracle的锁和锁的分类
- Oracle从创建用户到导入导出数据
- 51 nod 1022 石子归并 V2(dp决策单调性)
- Python 读取.xml数据集
- 多线程MFC处理视频
- Error:Execution failed for task ':app:processDebugManifest'. > Manifest merger failed with multiple
- hdu 4004 The Frog's Games
- windows进程间的通信