1. 程式人生 > >實現隱藏滾動條同時又可以滾動

實現隱藏滾動條同時又可以滾動

移動端頁面為了更接近原生的體驗,是否可以隱藏滾動條,同時又保證頁面可以滾動?

使用 overflow:hidden 隱藏滾動條,但存在的問題是:頁面或元素失去了滾動的特性。
由於只需要相容移動瀏覽器(Chrome 和 Safari),於是想到了自定義滾動條的偽物件選擇器
::-webkit-scrollbar

應用如下 CSS 可以隱藏滾動條:

.element::-webkit-scrollbar {display:none}

如果要相容 PC 其他瀏覽器(IE、Firefox 等),國外一位才人 John Kurlak 也研究出了一種辦法。在容器外面再巢狀一層 overflow:hidden

 內部內容再限制尺寸和外部巢狀層一樣,就變相隱藏了。

複製程式碼
 <div class="outer-container">
     <div class="inner-container">
        <div class="content">
            ......
        </div>
     </div>
 </div>
.outer-container,.content {
    width: 200px; height: 200px;
}
.outer-container {
    position: relative;
    overflow: hidden;
}
.inner-container {
    position: absolute; left: 0;
    overflow-x: hidden;
    overflow-y: scroll;
}

 /* for Chrome */
.inner-container::-webkit-scrollbar {
    display: none;
}
複製程式碼

https://blog.niceue.com/front-end-development/hide-scrollbar-but-still-scrollable-using-css.html