js之实现滚动条效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
border:none;
}
#box{
width: 800px;
height: 200px;
border: 1px solid #ddd;
position: relative;
margin: 100px auto;
overflow: hidden;
}
#box ul{
width: 2600px;
position: absolute;
left: 0;
top: 20px;
}
#box ul li{
float: left;
}
#box_bottom{
position: absolute;
left: 0;
bottom: 0;
background-color: #e8e8e8;
width: 100%;
height: 25px;
}
.mask{
position: absolute;
left: 0;
top:0;
width:100px;
height: 25px;
background-color: #aaa;
border-radius: 12px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<ul id="box_top">
<li><img src="images/img1.jpg" alt=""></li>
<li><img src="images/img2.jpg" alt=""></li>
<li><img src="images/img3.jpg" alt=""></li>
<li><img src="images/img4.jpg" alt=""></li>
<li><img src="images/img5.jpg" alt=""></li>
<li><img src="images/img6.jpg" alt=""></li>
<li><img src="images/img7.jpg" alt=""></li>
<li><img src="images/img8.jpg" alt=""></li>
<li><img src="images/img1.jpg" alt=""></li>
<li><img src="images/img2.jpg" alt=""></li>
<li><img src="images/img1.jpg" alt=""></li>
<li><img src="images/img2.jpg" alt=""></li>
<li><img src="images/img3.jpg" alt=""></li>
<li><img src="images/img4.jpg" alt=""></li>
<li><img src="images/img5.jpg" alt=""></li>
<li><img src="images/img6.jpg" alt=""></li>
<li><img src="images/img7.jpg" alt=""></li>
<li><img src="images/img8.jpg" alt=""></li>
<li><img src="images/img1.jpg" alt=""></li>
<li><img src="images/img2.jpg" alt=""></li>
</ul>
<div id="box_bottom">
<span class="mask"></span>
</div>
</div>
<script>
window.onload = function () {
//获取需要的标签
var box = document.getElementById("box");
var box_top = document.getElementById("box_top");
var box_bottom = document.getElementById("box_bottom");
var mask = box_bottom.children[0];
//滚动条的长度
// 滚动条长度 = ( 盒子的宽度 / 内容的宽度) * 盒子的宽度
var mask_len = (box.offsetWidth / box_top.offsetWidth) * box.offsetWidth;
mask.style.width = mask_len + 'px';
//鼠标事件
mask.onmousedown = function (event) {
var e = event || window.event;
//求出初始值
var beginX = e.clientX - mask.offsetLeft;
document.onmousemove = function (event) {
var e = event || window.event;
//求出移动的距离
var endX = event.clientX - beginX;
// 滚动边界值
if(endX < 0){
endX = 0;
}else if(endX >= box.offsetWidth - mask.offsetWidth){
endX = box.offsetWidth - mask.offsetWidth;
}
//运动效果
mask.style.left = endX + 'px';
// 内容走的距离 = (内容的长度 - 盒子的长度) \/ (盒子长度 - 滚动条的长度) * 滚动条走的距离
var content_len = (box_top.offsetWidth - box.offsetWidth) / (box.offsetWidth - mask.offsetWidth) * endX;
box_top.style.left = -content_len + 'px';
return false;
};
document.onmouseup = function () {
document.onmousemove = null;
}
}
}
</script>
</body>
</html>
本文来自博客园,作者:JackieDYH,转载请注明原文链接:https://www.cnblogs.com/JackieDYH/p/17634765.html