1.滚动条出现的原因是元素里面的内容超出元素本身的大小
元素的所有子元素的高度和 = 元素滚动条可滚动的距离 + 元素可见大小
2.通过元素获取到元素内部子元素的高度和和元素可见高度,可求得元素滚动条可滚动的距离
3.通过监听元素的scroll事件获取元素滚动条的滚动距离,求得当前滚动距离占可滚动位置的百分比
当前滚动条滚动的距离 / 元素可滚动的距离
4.(再用元素可见高度 乘 滚动的百分比)减 滚动条的高 可以动态设置滚动条的滚动位置。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>原生滚动条</title>
<style>
.wrapper{
position: relative;
width: 300px;
height: 300px;
overflow:hidden;
z-index:2;
font-size: 0;
}
.wrapper .content{
margin: 0;
padding: 16px 0;
border: 1px solid #000;
font-size:32px !important;
}
.wrapper .content:nth-child(odd){
ackground-color: #ccc;
}
.box{
position: absolute;
top: 0;
width: 320px;
height: 300px;
overflow: hidden auto;
background-color:#3ff;
}
#scroll_bar{
position: absolute;
right: 0;
top: 0;
height: 80px;
width: 6px;
z-index:2222;
background-color: #666;
border-radius: 2px;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="scroll_bar"></div>
<div class="box">
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
<p class="content">我是内容</p>
</div>
</div>
<script>
const wrapper = document.getElementsByClassName('wrapper')[0]
const box = document.getElementsByClassName('box')[0]
const contentList = document.getElementsByClassName('content')
const scroll_bar = document.getElementById('scroll_bar')
//元素可视高度
let v_height = wrapper.offsetHeight
// 元素真实高度
let r_height = contentList[0].offsetHeight * contentList.length
// 滚动条可滚动高度
let s_height = r_height - v_height
box.onscroll = function(e){
if(r_height <= v_height){
scroll_bar.style.display = 'none'
return
} else {
// 根据比例,求出滚动条可设置的位置
let place = this.scrollTop /s_height * v_height
// 限制滚动条最大高度
if(place - 80 < 0) {
scroll_bar.style.top = 0
return
}
scroll_bar.style.top = place - 80 + 'px'
}
}
</script>
</body>
</html>