专业编程基础技术教程

网站首页 > 基础教程 正文

自定义滚动条(怎么让滚动条自动滑动)

ccvgpt 2024-07-24 11:16:19 基础教程 76 ℃

<!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%;

}

.box{

width: 50%;

}

.bar{

background: #000;

width: 10px;

position: absolute;

top: 0;

right: 0;

}

.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> </body>

<script>

var $wrap = document.getElementById("wrap");var $boxMidle = document.getElementById("boxMidle");var $content = document.getElementById("content");var $bar = document.getElementById("bar");var isAuto = false$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 = isAuto?barHeight + "px":'100px' }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 =isAuto? this.scrollTop*rate + "px":this.scrollTop*($boxMidle.clientHeight-100)/($boxMidle.scrollHeight-$boxMidle.clientHeight)+'px';}
function debounce(fun,delay){ let timer; return function(){ if(timer){ clearTimeout(timer); timer=setTimeout(()=>{ fun() },delay) }else{ fun() } }}function throttle(){
} </script></html>

Tags:

最近发表
标签列表