<!DOCTYPE?html>
<html?lang="en">
<head>
????<meta?charset="UTF-8">
????<meta?name="viewport"?content="width=device-width,?initial-scale=1.0">
????<meta?http-equiv="X-UA-Compatible"?content="ie=edge">
????<title>Document</title>
????<style>
????????.wrap?{
????????????position:?relative;
????????????border:?1px?solid?#000;
????????????width:?400px;
????????????height:?400px;
????????????padding-right:?10px;
????????????overflow:?hidden;
????????}
????????.scrollBar?{
????????????position:?absolute;
????????????right:?0;
????????????top:?0;
????????????width:?10px;?
????????????height:?100%;
????????????background:?#ccc;
????????}
????????.scrollBar?span?{
????????????position:?absolute;
????????????right:?0;
????????????top:?0;
????????????width:?10px;
????????????background:?#000;
????????????min-height:?20px;
????????????border-radius:?5px;;
????????}
????????.list?{
????????????position:?absolute;
????????????left:?0;
????????????top:?0;
????????????width:?400px;
????????????margin:?0;
????????????padding:?0;
????????????list-style:?none;
????????}
????</style>
</head>
<body>
<div?class="wrap">
????<ul?class="list"></ul>
????<div?class="scrollBar">
????????<span></span>
????</div>
</div>
<script?src="fns.js"></script>
<script>
//?列表內(nèi)容
{
????let?list?=?document.querySelector(".list");
????list.innerHTML?=?[...(".".repeat(5000))].map((item,index)=>{
????????return?`<li>這是第${index}個li</li>`
????}).join("");
}
//?顯示區(qū)域高度/內(nèi)容總高度?=?滾動條高度/滾動軌道高度
//?滾動條高度?=?顯示區(qū)域高度/內(nèi)容總高度*滾動軌道高度;
//?自定義滾動條
{
????let?wrap?=?document.querySelector(".wrap");
????let?list?=?document.querySelector(".list");
????let?scrollBar?=?document.querySelector(".scrollBar?span");
????//?按照比例設(shè)置滾動條高度
????let?scrollBarH?=?wrap.clientHeight/list.offsetHeight*wrap.clientHeight;
????css(scrollBar,"height",scrollBarH);
????//?滾動條拖拽
????let?startEl?=?0;
????let?startMouse?=?0;
????let?move?=?(e)=>{
????????let?nowMouse?=?e.clientY;
????????let?disMouse?=?nowMouse?-?startMouse;
????????let?nowY?=?disMouse?+?startEl;
????????//?限制滾動條范圍
????????nowY?=?Math.max(0,nowY);//?最小值限制
????????nowY?=?Math.min(wrap.clientHeight?-?scrollBar.offsetHeight,nowY);//?最大值限制
????????css(scrollBar,"top",nowY);
????};
????scrollBar.addEventListener("mousedown",(e)=>{
????????startMouse?=?e.clientY;
????????startEl?=?css(scrollBar,"top");
????????document.addEventListener("mousemove",move);
????????document.addEventListener("mouseup",()=>{
????????????document.removeEventListener("mousemove",move);
????????},{once:true});
????????e.preventDefault();
????});
}
</script>
</body>
</html>