<!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>
自定义滚动条
于 2021-07-09 17:28:36 首次发布