移動端滾動穿透問題完美解決方案
2016年6月1日
目錄
- 問題
- css 之 overflow: hidden
- js 之 touchmove + preventDefault
- 解決方案 position: fixed
- document.scrollingElement
- 參考
問題
衆所周知,移動端當有 fixed 遮罩背景和彈出層時,在螢幕上滑動能夠滑動背景下面的内容,這就是臭名昭著的滾動穿透問題
之前搜尋了一圈,找到下面兩種方案
css 之 overflow: hidden
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
position: fixed
CSS
body .modal-open { position: fixed; width: 100%; } |
如果隻是上面的 css,滾動條的位置同樣會丢失
是以如果需要保持滾動條的位置需要用 js 儲存滾動條位置關閉的時候還原滾動位置
JavaScript
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/
擷取最佳閱讀體驗并參與讨論,請通路原文