原生js实现模拟滚动条加完整注释,包你看得懂

实现效果:
在这里插入图片描述
代码加注释如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equ

iv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
.box{
    width: 200px;
    height: 400px;
    position: relative;
    overflow: hidden;
    border: 1px solid red;
    display:inline-block
}
.content{
    width: 200px;
    height: 400px;
    position: absolute;
    top:0;
    left: 0;
}
.allbar{
    width: 20px;
    height: 400px;
    background: #ccc;
    position: relative;
    display:inline-block
}
.bar{
    width: 20px;
    height: 20px;
    background: orange;
    position: absolute;
    top: 0;
    left: 0;
}
</style>
<body>
    <div class="box">
        <div class="content">你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复你说的多久交货时间的环境从NSA采集卡说不出世界顶级卡刷积分哈时间和附近发生江哈斯记得哈十分骄傲是否发哈就是吉萨回复</div>
    </div>
    <div class="allbar">
        <div class="bar"></div>
    </div>
</body>
<script>
    var box=document.querySelector('.box')
    var content=document.querySelector('.content')
    var allbar=document.querySelector('.allbar')
    var bar=document.querySelector('.bar')
//第一步:求出滚动条高度
// 盒子高度/总内容和高度=滚动条高度/总滚动条高度
var height=box.offsetHeight/content.scrollHeight*allbar.offsetHeight;
// console.log(barHeight);
bar.style.height=height+'px'
//第二步:使滚动条能移动
bar.onmousedown=function(e){
    var e=e||window.event;
    //获取鼠标在滚动条中的位置
    var barHeight=e.pageY-allbar.offsetTop-bar.offsetTop;
    document.onmousemove=function(e){
    var e=e||window.event;
    //获取移动后的位置
    var barend=e.pageY-barHeight-allbar.offsetTop;
    // 判断是否到顶
    barend=barend>0?barend:0;
    //判断是否到底
    barend=barend>allbar.offsetHeight-bar.offsetHeight?allbar.offsetHeight-bar.offsetHeight:barend;
    // 对滚动条的高度赋值是其滚动
    bar.style.top=barend+'px';
    // 第三步:使内容滚动
    //算出滚动条最大能滚动的距离
    var maxBar=allbar.offsetHeight-bar.offsetHeight;
    console.log(maxBar)
    //算出内容块最大能滚动的距离
    var maxcontent=content.scrollHeight-content.offsetHeight;
    console.log(maxcontent)
    // 当前内容高度/最大能滚动的高度=当前滚动条高度/滚动条最大能滚动的高度
    var contenHeight=barend/maxBar*maxcontent;
    content.style.top=-contenHeight+'px'
    }
}
document.onmouseup=function(){
    document.onmousemove=null;
}
</script>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41988554/article/details/100587776