隱藏滾動條的同時還需要支持滾動,我們經常在前端開發中遇到這種情況,最容易想到的是加一個iscroll插件,但其實現在CSS也可以實現這個功能,我已經在很多地方使用了,下面一起看看這三種方法。
方法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:使用三個容器包圍起來,不需要計算滾動條的寬度
該代碼最早是在Microsoft博客上看到的,跟我上面的思路差不多,只不過人家里面又加多了一個盒子,將內容限制在盒子里面了。這樣子就看不到滾動條同時也可以滾動。
代碼如下:·
<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:css隱藏滾動條
同時該文章還分享了一種通過CSS隱藏滾動條的方法,不過這個方法不兼容IE,做移動端的可以使用。
那就是自定義滾動條的偽對象選擇器::-webkit-scrollbar,詳情請看之前的文章:CSS3自定義webkit滾動條樣式
chrome 和Safari
.element::-webkit-scrollbar { width: 0 !important }
IE 10+
.element { -ms-overflow-style: none; }
Firefox
//code from http://caibaojian.com/hide-scrollbar.html
.element { overflow: -moz-scrollbars-none; }