問題
眾所周知,移動端當有 fixed 遮罩背景和彈出層時,在屏幕上滑動能夠滑動背景下面的內容,這就是著名的滾動穿透問題
之前搜索了一圈,找到下面兩種方案
css 之 overflow: hidden
.modal-open {
&, body {
overflow: hidden;
height: 100%;
}
}
頁面彈出層上將 .modal-open
添加到 html 上,禁用 html 和 body 的滾動條
但是這個方案有兩個缺點:
- 由於 html 和 body的滾動條都被禁用,彈出層后頁面的滾動位置會丟失,需要用 js 來還原
- 頁面的背景還是能夠有滾的動的效果
js 之 touchmove + preventDefault
modal.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
這樣用 js 阻止滾動后看起來效果不錯了,但是也有一個缺點:
- 彈出層里不能有其它需要滾動的內容(如大段文字需要固定高度,顯示滾動條也會被阻止)
上面兩個方案都有缺點,今天用英文關鍵字 google 了一下,才發現原來還有更好的方案
解決方案 position: fixed
body.modal-open {
position: fixed;
width: 100%;
}
如果只是上面的 css,滾動條的位置同樣會丟失
所以如果需要保持滾動條的位置需要用 js 保存滾動條位置關閉的時候還原滾動位置
這樣上面3個缺點都解決了,至此滾動穿透就完美解決了
參考
- https://github.com/twbs/bootstrap/issues/15852
- https://github.com/mathiasbynens/document.scrollingElement
- https://segmentfault.com/q/1010000002942948
原文地址:http://uedsky.com/2016-06/mobile-modal-scroll/
獲取最佳閱讀體驗並參與討論,請訪問原文