方法1:計算滾動條寬度並隱藏起來
<div class="outer-container"> <div class="inner-container"> ...... </div> </div> .outer-container{ width: 360px; height: 200px; position: relative; overflow: hidden; } .inner-container{ position: absolute; left: 0; top: 0; right: -17px; bottom: 0; overflow-x: hidden; overflow-y: scroll; }注釋:這個代碼巧妙的向右移動了17個像素,剛好等於滾動條的寬度。這個值是我手動調試得來的。在chrome和IE沒發現問題。
方法2:使用三個容器包圍起來,不需要計算滾動條的寬度
這個方法相對於方法1多加了一個盒子,將內容限制在盒子里面了,這樣就看不到滾動條的同時也可以滾動。
<div class="outer-container"> <div class="inner-container"> <div class="content"> ...... </div> </div> </div> .element, .outer-container { width: 200px; height: 200px; } .outer-container { border: 5px solid purple; position: relative; overflow: hidden; } .inner-container { position: absolute; left: 0; overflow-x: hidden; overflow-y: scroll; } .inner-container::-webkit-scrollbar { display: none; }
方法3:自定義滾動條的偽對象選擇器::webkit-scrollbar
這種方法不兼容IE,做移動端的可以使用。
.element::-webkit-scrollbar { width: 0 !important }IE 10+
.element { -ms-overflow-style: none; }Firefox
.element { overflow: -moz-scrollbars-none; }
詳情:
以下為自定義webkit滾動條樣式
使用谷歌Chrome瀏覽器的最新版本,滾動條樣式已經是非常漂亮了。這個webkit-scrollbar僅適用於webkit內核。
webkit屬性
::-webkit-scrollbar { /* 1 */ } ::-webkit-scrollbar-button { /* 2 */ } ::-webkit-scrollbar-track { /* 3 */ } ::-webkit-scrollbar-track-piece { /* 4 */ } ::-webkit-scrollbar-thumb { /* 5 */ } ::-webkit-scrollbar-corner { /* 6 */ } ::-webkit-resizer { /* 7 */ }
使用實例
::-webkit-scrollbar { width: 12px; } ::-webkit-scrollbar-track { background-color: #eaeaea; border-left: 1px solid #ccc; } ::-webkit-scrollbar-thumb { background-color: #ccc; } ::-webkit-scrollbar-thumb:hover { background-color: #aaa; } ::-webkit-scrollbar-thumb:active{ background-color:#333; }不同狀態
:horizontal //horizontal偽類適用於任何水平方向上的滾動條 :vertical //vertical偽類適用於任何垂直方向的滾動條 :decrement //decrement偽類適用於按鈕和軌道碎片。表示遞減的按鈕或軌道碎片,例如可以使區域向上或者向右移動的區域和按鈕 :increment //increment偽類適用於按鈕和軌道碎片。表示遞增的按鈕或軌道碎片,例如可以使區域向下或者向左移動的區域和按鈕 :start //start偽類適用於按鈕和軌道碎片。表示對象(按鈕 軌道碎片)是否放在滑塊的前面 :end //end偽類適用於按鈕和軌道碎片。表示對象(按鈕 軌道碎片)是否放在滑塊的后面 :double-button //double-button偽類適用於按鈕和軌道碎片。判斷軌道結束的位置是否是一對按鈕。也就是軌道碎片緊挨着一對在一起的按鈕。 :single-button //single-button偽類適用於按鈕和軌道碎片。判斷軌道結束的位置是否是一個按鈕。也就是軌道碎片緊挨着一個單獨的按鈕。 :no-button no-button偽類表示軌道結束的位置沒有按鈕。 :corner-present //corner-present偽類表示滾動條的角落是否存在。 :window-inactive //適用於所有滾動條,表示包含滾動條的區域,焦點不在該窗口的時候。 ::-webkit-scrollbar-track-piece:start { /*滾動條上半邊或左半邊*/ } ::-webkit-scrollbar-thumb:window-inactive { /*當焦點不在當前區域滑塊的狀態*/ } ::-webkit-scrollbar-button:horizontal:decrement:hover { /*當鼠標在水平滾動條下面的按鈕上的狀態*/ }

