H5页面滚动时显示滚动条,不滚动时隐藏滚动条

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滚动条滑动显示不滑动隐藏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            overflow: -moz-hidden-unscrollable;
            height: 100%;
        }
        body::-webkit-scrollbar{
            width: 0px;
        }
        body {
            -ms-overflow-style: none;
            height: 100%;
            width: calc(100vw + 18px);
            overflow: auto;
        }
        #box::-webkit-scrollbar {
            width: 6px;
            height: 6px
        }
        
        #box::-webkit-scrollbar-thumb {
            border-radius: 3px;
            -moz-border-radius: 3px;
            -webkit-border-radius: 3px;
            background-color: #666;
        }
        
        #box::-webkit-scrollbar-track {
            background-color: #eee;
        }
        #box {
            width: calc(100vw - 0px);
            height: 100%;
            overflow-y: scroll;
        }
        .small {
            height: 3000px;
        }
    </style>
</head>
<body>
    <div id="box">
        <div class="small"></div>
    </div>

    <script>
        let roll = 0; // 滚动的值
        let stop = 0; // 对比时间的值
        let timer = null;
        document.getElementById('box').addEventListener('scroll', function(){
            var e = event || event.target;
            // console.log(e.srcElement.scrollTop)
            // 每次滑动前都清除一遍我们定义的定时器
            clearTimeout(timer);
            // 每次滚动的时候,都让box回到原来的宽度
            document.getElementById('box').style.width = 'calc(100vw - 0px)';
            // 这里我设置的是300毫秒,您可以更改您想要的间隔秒数
            timer = setTimeout("JudgeScroll()", 300);
            roll = e.srcElement.scrollTop;
        })
        function JudgeScroll() {
            // console.log(roll,stop)
            stop = document.getElementById('box').scrollTop;
            if(stop == roll) {
                // console.log('滚动停止');
                // 判断如果相等,就把box宽度增加18px,达到隐藏滚动条的效果
                document.getElementById('box').style.width = 'calc(100vw + 18px)';
            }
        }
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_45609680/article/details/130429565
今日推荐