隱藏滾動條的同時還須要支持滾動,咱們常常在前端開發中遇到這種狀況,最容易想到的是加一個iscroll插件,但其實如今CSS也能夠實現這個功能,我已經在不少地方使用了,下面一塊兒看看這三種方法。css
方法1:計算滾動條寬度並隱藏起來
在本站的側欄,你能夠看到前端日報的那塊內容並無滾動條,但鼠標移上去卻能夠滾動內容。這是什麼技術呢? 其實我只是把滾動條經過定位把它隱藏了起來。html
演示前端
下面給一個簡化版的代碼css3
1 <div class="outer-container"> 2 <div class="inner-container"> 3 ...... 4 </div> 5 </div> 6 .outer-container{ 7 width: 360px; 8 height: 200px; 9 position: relative; 10 overflow: hidden; 11 } 12 .inner-container{ 13 position: absolute; 14 left: 0; 15 top: 0; 16 right: -17px; 17 bottom: 0; 18 overflow-x: hidden; 19 overflow-y: scroll; 20 }
這個代碼巧妙的向右移動了17個像素,恰好等於滾動條的寬度。這個值是我手動調試得來的。在chrome和IE沒發現問題。web
方法2:使用三個容器包圍起來,不須要計算滾動條的寬度
該代碼最先是在Microsoft博客上看到的,跟我上面的思路差很少,只不過人家裏面又加多了一個盒子,將內容限制在盒子裏面了。這樣子就看不到滾動條同時也能夠滾動。chrome
代碼以下:ide
1 <div class="outer-container"> 2 <div class="inner-container"> 3 <div class="content"> 4 ...... 5 </div> 6 </div> 7 </div> 8 .element, .outer-container { 9 width: 200px; 10 height: 200px; 11 } 12 13 .outer-container { 14 border: 5px solid purple; 15 position: relative; 16 overflow: hidden; 17 } 18 19 .inner-container { 20 position: absolute; 21 left: 0; 22 overflow-x: hidden; 23 overflow-y: scroll; 24 } 25 26 .inner-container::-webkit-scrollbar { 27 display: none; 28 }
方法3:css隱藏滾動條
同時該文章還分享了一種經過CSS隱藏滾動條的方法,不過這個方法不兼容IE,作移動端的能夠使用。post
那就是自定義滾動條的僞對象選擇器::-webkit-scrollbar,詳情請看以前的文章:CSS3自定義webkit滾動條樣式url
1 &::-webkit-scrollbar{ 2 background-color:transparent; 3 }
chrome 和Safarispa
.element::-webkit-scrollbar { width: 0 !important }
IE 10+
.element { -ms-overflow-style: none; }
Firefox
.element { overflow: -moz-scrollbars-none; }