如何隱藏滾動條但又能滾動,不用js實現(轉載)

原文地址:https://segmentfault.com/q/1010000006863477

知乎很多這樣提問的,但是很多回答的人都不懂我們到底要什麼。
有人說overflow:hidden;啊可以隱藏滾動條啊。
是啊,是可以隱藏但不能滾動啊。當然用js的方法我就不說了,不靠譜(畢竟要加載完才能設置高度,不然一開始拿div的高度一般是不正確的,所以說我不想用js實現)。

純css實現呢,我只能兼容IE9或者以上。
首先是webkit,::-webkit-scrollbar{width: 0;}這個僞類是很好可惜只有webkit支持。
我下面說的方法是包括火狐谷歌IE(9和9+)都支持,但是得用局部滾動overflow:auto;
最簡單的demo:
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <title></title>
    <meta name="renderer" content="webkit">
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        html,
        body {
            height: 100%;
        }
        
        html {
            overflow: hidden;
        }
        
        body {
            overflow: auto;
            width: calc(100vw + 20px);
        }
        
        .page {
            height: 200%;
            border: 1px dashed;
            width: 100vw;
        }
    </style>
</head>

<body>
    <div class="page">
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
        <p>我是文字啊啊啊啊啊th</p>
    </div>
</body>

</html>
說說原理吧,首先是vw,vh這種css3單位不懂請百度,讓body寬度是窗口寬度加上20px(瀏覽器滾動條差不多這個寬度),.page裏面的寬度是100%視口也就是100vw,這樣body的滾動條就被隱藏了(超出部分被html隱藏)。
優點:不用js(js必須頁面加載完拿高度才準確)。
缺點:1、IE8不支持,2、移動端不用測試了,移動端滾動條沒那麼簡單,3、overflow:auto;局部滾動在火狐瀏覽器滾動速度變慢不知道爲什麼。

求有沒有方法能解決第1,3個缺點的,要求不用js。


來源:Hide scroll bar, but still being able to scroll

作者: @Mr_Green

Just a test which is working fine.

#parent{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#child{
    width: 100%;
    height: 100%;
    overflow-y: scroll;
    padding-right: 17px; /* Increase/decrease this value for cross-browser compatibility */
}

Working Fiddle點擊預覽

JavaScript:

Since, the scrollbar width differs in different browsers, it is better to handle it with JavaScript. If you do Element.offsetWidth - Element.clientWidth, the exact scrollbar width will show up.

JavaScript Working Fiddle點擊預覽

or

Using Position: absolute,

#parent{
    height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
}

#child{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: -17px; /* Increase/Decrease this value for cross-browser compatibility */
    overflow-y: scroll;
}

Working Fiddle點擊預覽

JavaScript Working Fiddle點擊預覽

Info:

Based on this answer, I created a simple scroll plugin. I hope this will help someone.

移步這裏,純 css 實現 PC 端無滾動條滾動樣式:https://codepen.io/gongph/pen...點擊預覽


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章