image.png
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 300px;
height: 500px;
border: 1px solid red;
margin: 100px;
position: relative;
overflow: hidden;
/* 不让文字被选中 */
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.content {
padding: 5px 18px 5px 5px;
position: absolute;
top: 0;
left: 0;
}
.scroll {
width: 18px;
height: 100%;
position: absolute;
top: 0;
right: 0;
background-color: #eee;
}
.bar {
height: 100px;
width: 100%;
position: absolute;
top: 0;
left: 0;
background-color: red;
border-radius: 10px;
cursor: pointer;
}
</style>
<body>
<div class="box" id="box">
<div class="content" id="content">
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,
我是文字内容,我是文字内容,我是文字内容,1
</div>
<div class="scroll" id="scroll">
<div class="bar" id="bar"></div>
</div>
</div>
<script>
var box = my$('box');
var content = my$('content');
var scroll = my$('scroll');
var bar = my$('bar');
//1.根据内容计算滚动条的高度
// offsetHeight = 元素大小 + padding + border
// clientHeight = 元素大小 + padding
// scrollHeight = 内容大小 + padding
// bar的高度/scroll的高度 = box的高度/content的高度
// 当内容的高度大于box的高度,再计算滚动条的高度,否则滚动条的高度为0
var barHeight = 0;
if (content.scrollHeight > box.clientHeight) {
barHeight = box.clientHeight * scroll.clientHeight / content.scrollHeight;
}
bar.style.height = barHeight + 'px';
//2.让滚动条能拖拽
bar.onmousedown = function (e) {
e = e || window.event;
// 获取鼠标的位置
// 鼠标在scroll中的位置 = 鼠标在页面中的位置 - box在页面中的位置 - bar在scroll中的位置
var scrollY = getPage(e).pageY - box.offsetTop - bar.offsetTop; //这个值是在鼠标按下就要求的
document.onmousemove = function (e) {
e = e || window.event;
var y = getPage(e).pageY - box.offsetTop - scrollY;
// 控制y不能移出父元素
y = y < 0 ? 0 : y;
y = y > scroll.clientHeight - bar.clientHeight ? scroll.clientHeight - bar.clientHeight : y;
// console.log(scrollY,y, bar.offsetTop);
bar.style.top = y + 'px';
//3.当拖拽滚动条,内容也跟着滚动
// 内容滚动的距离/内容最大能滚动的距离 = 滚动条滚动的距离/滚动条最大能滚动的距离
var contentMax = content.scrollHeight - box.clientHeight;
var barMax = scroll.clientHeight - bar.clientHeight;
var contentY = bar.offsetTop * contentMax / barMax;
content.style.top = -contentY + 'px';
}
}
document.onmouseup = function () {
document.onmousemove = null;
}
</script>
</body>
网友评论