<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模拟导航条</title>
<style>
#box{
position: relative;
width: 300px;
height: 500px;
overflow: hidden;
border:1px solid red;
}
#content {
display: block;
position: absolute;
left:0px;
top:0px;
padding-right: 10px;
/*不能复制文本*/
user-select:none;
}
#scroll {
height: 500px;
width: 10px;
background-color: #333;
float: right;
position: relative;
}
#bar {
position: absolute;
top:0px;
left:0px;
width:10px;
border-radius: 5px;
background-color: #eee;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<span id="content">
我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测试模拟导航条我在测
</span>
<div id="scroll">
<div id="bar">
</div>
</div>
</div>
<script>
var $e = function(ele){
return document.getElementById(ele);
}
var box = $e("box");
var content = $e("content");
var scroll = $e("scroll");
var bar = $e("bar");
//算出滚动条的高度
//box高度/content高度 = bar高度/scroll高度
var contentHeight = content.scrollHeight;
var boxHeight = box.clientHeight;
var scrollHeight = scroll.clientHeight;
if(contentHeight>boxHeight){
var barHeight = scrollHeight*boxHeight/contentHeight;
console.log(contentHeight+":"+boxHeight+":"+barHeight);
bar.style.height = barHeight+"px";
}else{
scroll.style.display = "none";
content.style.paddingRight = "0px";
}
//鼠标放在bar上,拖动可实现bar的拖动
bar.onmousedown =function(e){
e = e||window.event;
var barTop = bar.offsetTop;
var scrollTop = scroll.offsetTop;
var boxTop = box.offsetTop;
var y = e.pageY - scrollTop- barTop;
document.onmousemove = function(e){
e = e||window.event;
var barY =e.pageY-boxTop - y;
// 控制bar在scroll中间移动
barY = barY<=0 ? 0 : barY;
//此处只能用barHeight,不能用bar.style.height 因为bar.style.height包含单位的字符串,转化数字失败会返回NAN
barY = barY>(scrollHeight - barHeight)?(scrollHeight - barHeight):barY;
console.log(barY);
bar.style.top = barY+"px";
// 文本滚动的距离/文本最大能滚动的距离 = 滚动条滚动的距离/滚动条最大能滚动的距离
var contentScrollHeight = barY*(contentHeight-boxHeight)/(scrollHeight-barHeight);
content.style.top = -contentScrollHeight+"px";
}
}
document.onmouseup = function(){
document.onmousemove = function(){};
}
</script>
</body>
</html>
模拟导航条
猜你喜欢
转载自blog.csdn.net/weixin_40098371/article/details/82872553
今日推荐
周排行