客户要求一定要一直显示滚动条,但是苹果的浏览器会隐藏滚动条,笔者尝试后找不到让苹果浏览器的滚动条一直显示的办法,于是自己写了个(伪)滚动条。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<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){
background-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;
}
.scroll {
width: 18px;
height: 100%;
position: absolute;
top: 0;
right: 0;
background-color: #eee;
z-index: 5;
}
.bar {
height: 100px;
width: 100%;
position: absolute;
top: 0;
left: 0;
background-color: red;
border-radius: 10px;
cursor: pointer;
z-index: 6;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="scroll" class="scroll">
<div id="bar" class="bar"></div>
</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')
let scroll = document.getElementById("scroll");
let bar = document.getElementById("bar");
//bar高度
let sumHeght = 0;
for(let i = 0 ; i < contentList.length ; i++){
sumHeght += contentList[i].offsetHeight
}
console.log("sumHeght",sumHeght);
let height = scroll.offsetHeight * wrapper.offsetHeight / sumHeght;
bar.style.height = height + "px";
//元素可视高度
let v_height = wrapper.offsetHeight
// 元素真实高度
let r_height = contentList[0].offsetHeight * contentList.length
// 滚动条可滚动高度
let s_height = r_height - v_height + (height * 2.75);
box.onscroll = function(e){
if(r_height <= v_height){
bar.style.display = 'none'
return
} else {
// 根据比例,求出滚动条可设置的位置
let place = (this.scrollTop) * ((v_height - height)/(r_height - v_height))
// 限制滚动条最大高度
if(place < 0) {
bar.style.top = 0;
return
}
bar.style.top = place + 'px'
}
}
</script>
</body>
</html>