移動端滾動穿透問題完美解決方案


問題

眾所周知,移動端當有 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 保存滾動條位置關閉的時候還原滾動位置

/**
* 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





 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM