素材牛VIP会员
如何隐藏滚动条但又能滚动,不用js实现
 赵***2  分类:Html5  人气:1206  回帖:1  发布于6年前 收藏

知乎很多这样提问的,但是很多回答的人都不懂我们到底要什么。
有人说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。

 标签:csshtml5

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv5 码农
错***7 Linux系统工程师 6年前#1

来源: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.

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取