1.滚动条的高度 = 容器的高度/内容的高度*容器的高度
2.内容移动的距离=(内容的高度-容器的高度) / (容器的高度-滚动条的高度) * 滚动条移动的距离
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 300px;
height: 500px;
border: 1px solid red;
margin: 100px;
position: relative;
overflow: hidden;
}
.content{
height: auto;
padding-right: 20px;
position: absolute;
top: 0;
left: 0;
padding: 5px 20px 5px 5px;
}
.scroll{
width: 20px;
height: 100%;
background-color: #eee;
position: absolute;
right: 0;
top: 0;
}
.bar{
width: 100%;
height: 100px;
background-color: red;
cursor: pointer;
border-radius:10px;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="content">
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容这里是内容
</div>
<div class="scroll">
<div class="bar"></div>
</div>
</div>
</body>
</html>
<script>
var box = document.getElementById("box");
var content = box.children[0];
var scroll = box.children[1];
var bar = scroll.children[0];
//滚动条的高度 = 容器的高度/内容的高度*容器的高度
if(content.offsetHeight<=box.offsetHeight){
bar.style.height = 0;
}else{
bar.style.height = box.offsetHeight*scroll.offsetHeight/content.offsetHeight +"px";
}
//拖动滚动条
bar.onmousedown = function (event) {
var event = event || window.event;
//var val = event.clientY - scroll.offsetHeight;
var val = event.clientY - this.offsetTop;
document.onmousemove = function (event) {
var event = event || window.event;
var barTop = event.clientY - val;
var conTop = (content.offsetHeight-box.offsetHeight)/(box.offsetHeight-bar.offsetHeight)*barTop;
if(barTop<0){
barTop = 0;
}else if(barTop > (box.offsetHeight - bar.offsetHeight)){
barTop = box.offsetHeight - bar.offsetHeight;
}else{
content.style.top = -conTop + "px";
}
bar.style.top = barTop +"px";
}
}
document.onmouseup = function () {
window.getSelection() ? window.getSelection().removeAllRanges() : document.selection.empty();
document.onmousemove = null;
}
</script>