预览


源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html, body {
padding: 0;
margin: 0;
height: 100%;
}
.box-content {
-ms-overflow-style: none;
scrollbar-width: none;
overflow: -moz-scrollbars-none;
}
.box-content::-webkit-scrollbar {
display: none
}
.box {
display: flex;
height: 100%;
}
.box > .box-content {
width: 100%;
overflow: auto;
}
.box > .box-content > p {
height: 500px;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
.box > .box-content > p > span {
color: #ffffff;
font-size: 40px;
}
.scroll-bar {
width: 20px;
background: #00b7ee;
}
.scroll-bar > div {
background: #030303;
}
.scroll-bar > div:active {
cursor: pointer;
}
</style>
</head>
<body>
<div class="box">
<div class="box-content">
<p style="background: #007bff">
<span>内容1</span>
</p>
<p style="background: #ae012b">
<span>内容2</span>
</p>
<p style="background: #357376">
<span>内容3</span>
</p>
<p style="background: #fe0138">
<span>内容4</span>
</p>
<p style="background: #ff6547">
<span>内容5</span>
</p>
<p style="background: #ff5400">
<span>内容6</span>
</p>
<p style="background: #bdbdbd">
<span>内容7</span>
</p>
<p style="background:#fdd997">
<span>内容8</span>
</p>
</div>
<div class="scroll-bar">
<div></div>
</div>
</div>
<script>
let count = 0;
let doc = document;
let box = doc.querySelector('.box');
let content = doc.querySelector('.box-content');
let scrollBar = doc.querySelector('.scroll-bar');
let scroll = doc.querySelector('.scroll-bar > div');
content.scrollTop = 0;
window.onresize = function () {
scroll.style.transform = `translateY(${Math.round(content.scrollTop / scrollBar.clientHeight * 100)}%)`;
return customScrollBar();
};
customScrollBar();
function customScrollBar() {
let boxTop = null;
let scrollBarHeight = scrollBar.clientHeight;
let contentSH = content.scrollHeight;
let contentCH = content.clientHeight;
let multiple = contentSH / contentCH;
let num = contentCH * (contentCH / contentSH);
scroll.style.height = `${num}px`;
if (contentCH >= contentSH) {
scrollBar.style.display = 'none'
} else if (scrollBar.style.display === 'none') {
scrollBar.style.display = 'block'
}
content.addEventListener('scroll', function () {
scroll.style.transform = `translateY(${Math.round(this.scrollTop / scrollBarHeight * 100)}%)`
});
function mouseEvents(e) {
content.scrollTop = ((e.clientY - boxTop) * multiple) - count
}
scroll.onmousedown = function (e) {
doc.onselectstart = function () {
return false;
};
boxTop = box.getBoundingClientRect().top;
count = e.offsetY * multiple;
box.addEventListener('mousemove', mouseEvents);
};
box.onmouseup = function () {
this.removeEventListener('mousemove', mouseEvents);
doc.onselectstart = function () {
return true;
}
};
box.onmouseleave = function () {
this.removeEventListener('mousemove', mouseEvents);
doc.onselectstart = function () {
return true;
}
}
}
</script>
</body>
</html>