实现滚动条
相关代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
html,body{
height: 100%;
overflow: hidden;
}
#wrap{
position: absolute;
top: 0;
right: 0;
width: 20px;
height: 100%;
background-color: #9ACD32;
}
#inner{
position: absolute;
top: 0;
left: 0;
width: 100%;
background-color: chocolate;
}
#content{
position: absolute;
}
</style>
</head>
<body>
<div id="content"></div>
<div id="wrap">
<div id="inner"></div>
</div>
</body>
<script type="text/javascript">
var inner=document.getElementById('inner');
var content=document.getElementById('content');
//添加文本
for(var i=0;i<=1000;i++){
content.innerHTML+=i+'<br>';
}
//滚动条的高度
var scaleH=document.documentElement.clientHeight/content.offsetHeight;
inner.style.height=scaleH*document.documentElement.clientHeight+'px';
//定义目标元素的初始位置
var eleY=0;
//定义鼠标的初始位置
var mouseS=0;
//目标元素绑定鼠标点击事件
inner.onmousedown=function (event) {
//获取目标元素的初始位置
eleY=inner.offsetTop;
//鼠标的初始位置
mouseS=event.clientY;
document.onmousemove=function (event) {
//鼠标的结束位置
var mouseE=event.clientY;
//鼠标的差
var disY=mouseE-mouseS;
//目标元素的终止位置
var top=disY+eleY;
//范围限定
var topM=document.documentElement.clientHeight-inner.offsetHeight;
if(top<0){
top=0;
}else if(top>topM){
top=topM;
};
inner.style.top=top +'px';
var scale=top/document.documentElement.clientHeight;
content.style.top=-scale*(content.offsetHeight-document.documentElement.clientHeight)+'px';
}
document.onmouseup=function () {
//dom0解绑
document.onmousemove=document.onmouseup=null;
}
//清除系统默认行为
return false;
}
</script>
</html>