<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
.wrap {
width: 400px;
height: 400px;
border: 2px solid deeppink;
margin: 0 auto;
overflow: hidden;
position: relative;
}
.box-middle {
height: 100%;
overflow: auto;
width: 200%;
/* border: 2px solid blue; */
box-sizing: border-box;
}
.box {
width: 50%;
}
.bar {
background: #000;
width: 10px;
position: absolute;
top: 0;
right: 0;
/* border: 2px solid red; */
box-sizing: border-box;
z-index: 100;
}
.bar_bg {
background: #fff;
width: 10px;
height: 100%;
position: absolute;
top: 0;
right: 0;
/* border: 2px solid red; */
box-sizing: border-box;
z-index: 10;
}
.s1 {
height: 400px;
background: pink;
}
.s2 {
height: 400px;
background: deeppink;
}
.s3 {
height: 400px;
background: deepskyblue;
}
</style>
</head>
<body>
<div class="wrap" id="wrap">
<div class="box-middle" id="boxMidle">
<div class="box" id="content">
<div class="s1">内容1</div>
<div class="s2">内容2</div>
<div class="s3">内容3</div>
</div>
</div>
<div class="bar" id="bar"></div>
<div class="bar_bg"></div>
</div>
</body>
<script>
var $wrap = document.getElementById("wrap");
var $boxMidle = document.getElementById("boxMidle");
var $content = document.getElementById("content");
var $bar = document.getElementById("bar");
$content.style.width = $wrap.clientWidth + "px"; //内容的宽度
var rate = $boxMidle.clientHeight / $boxMidle.scrollHeight; //滚动条高度的比例,也是滚动条top位置的比例
var barHeight = rate * $boxMidle.clientHeight; //滚动条的 bar 的高度
if (rate < 1) {
//需要出现滚动条,并计算滚动条的高度
$bar.style.height = barHeight + "px";
} else {
//不需要出现滚动条
$bar.style.display = "none";
}
$boxMidle.onscroll = function (e) {
console.log("offsetHeight" + this.offsetHeight); //height + padding + border
console.log("clientHeight" + this.clientHeight); // height + padding
console.log("scrollHeight" + this.scrollHeight); //内容的高度(所有子元素高度和) + padding
console.log(this.scrollTop);
$bar.style.top = this.scrollTop * rate + "px";
}
</script>
</html>
css自定义滚动条
最新推荐文章于 2024-07-26 15:10:54 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)