自定义横向滚动条模拟

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值