自定义滚动条

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        #scroll{
            width: 5px;
            background: red;
            position: fixed;
            top:0;
            bottom:0;
        }
        #scroll_thumb{
            width: 100%;
            background: black;
        }
        #scroll_content{
            height: 2000px;
        }
    </style>
</head>
<body>
<div id="scroll">
    <div id="scroll_thumb"></div>
</div>
<div id="scroll_content">
</div>
<script>
    var scroll_thumb = document.getElementById('scroll_thumb');
    //计算网页可视区与自定义滚动条的高度比
    var heightProportion = window.innerHeight / document.body.scrollHeight;
    //计算自定义滚动条的轨道高
    var scroll_track_height = (document.body.scrollHeight - window.innerHeight) * heightProportion;
    //计算自定义滚动条中小方块的高
    var scroll_thumb_height = window.innerHeight - scroll_track_height;
    scroll_thumb.style = "height:"+scroll_thumb_height+"px";
    window.onscroll = function () {
        //根据页面卷起的高度计算自定义滚动条top距离
        var customScrollTop= document.documentElement.scrollTop * heightProportion;
        //设置自定义滚动条top距离
        scroll_thumb.style = "height:"+scroll_thumb_height+"px;"+'margin-top:'+ customScrollTop +'px';
    }
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

局外人LZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值