<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{padding: 0;margin: 0;list-style: none;}
#box{width: 792px;height: 300px;border: 1px solid #ddd;margin: 100px auto;position: relative;overflow: hidden;}
#box_top{position: absolute;left:0;top:20px;}
#box_top li{float: left;}
#box_bottom{width: 100%;position: absolute;left: 0;bottom: 0;background: #e8e8e8;height: 25px;}
#mask{height: 25px;background: orangered;border-radius: 12px;position: absolute;left: 0;top: 0;cursor: pointer;}
/*#box_top li img{
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}*/
</style>
</head>
<body>
<div id="box">
<ul id="box_top">
<li><img src="imgs/1.jpg"/></li>
<li><img src="imgs/13.jpg"/></li>
<li><img src="imgs/14.jpg"/></li>
<li><img src="imgs/15.jpg"/></li>
<li><img src="imgs/2.jpg"/></li>
<li><img src="imgs/22.jpg"/></li>
<li><img src="imgs/27.jpg"/></li>
<li><img src="imgs/28.jpg"/></li>
<li><img src="imgs/27.jpg"/></li>
<li><img src="imgs/28.jpg"/></li>
</ul>
<div id="box_bottom">
<span id="mask"></span>
</div>
</div>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementById("box")
var box_top = document.getElementById("box_top")
var box_bottom = document.getElementById("box_bottom")
var mask = document.getElementById("mask")
// 获取ul的总宽度
var li= box_top.children[0]
console.log(li.offsetWidth)
var liL = box_top.children[0].offsetWidth * box_top.children.length
box_top.style.width = liL + "px"
// 滚动条的长度 = (盒子的宽度 / 内容的宽度)*盒子的宽度
var mask_len = (box.offsetWidth / box_top.offsetWidth)*box.offsetWidth
mask.style.width = mask_len + "px"
// 鼠标操作
mask.onmousedown = function(e){
e = e || event
var beginX = e.clientX - mask.offsetLeft
document.onmousemove = function(e){
e = e || event
var endX = e.clientX - beginX
if(endX < 0){
endX = 0
}
if(endX >= box.offsetWidth - mask.offsetWidth){
endX = box.offsetWidth - mask.offsetWidth
}
mask.style.left = endX + "px"
// 内容走的距离 = (内容的长度 - 盒子的长度 )/ (盒子的长度 - 滚动条的长度)*滚动条走的距离
var contentL = (box_top.offsetWidth - box.offsetWidth)/(box.offsetWidth - mask.offsetWidth)*endX
box_top.style.left = -contentL + "px"
window.getSelection?window.getSelection().removeAllRanges():document.selection.empty()//防止拖动时选中内容
}
document.οnmοuseup= function(e){
e = e || event
document.onmousemove = null
}
}
}
</script>
</body>
</html>
自定义横向滚动条模拟
最新推荐文章于 2024-05-24 17:17:32 发布