赞
踩
点击导航栏左右拖动
CSS:
<style> .navBar { width: 1200px; margin-left: 25px; margin-top: 40px; margin-bottom: 40px; overflow-x: auto; white-space: nowrap; } /* 去除底部滚动条 */ .navBar::-webkit-scrollbar { display: none; } li { display: inline-table; height: 50px; line-height: 50px; padding-left: 35px; padding-right: 35px; margin-right: 12.5px; border-radius: 10px; background: #EEEEEE; font-family: " PingFangSC-Regular"; font-size: 30px; color: #333333; text-align: center; width: 300px; } </style>
HTML
<body>
<ul class="navBar" id="nav">
<li>拖动1</li>
<li>拖动2</li>
<li>拖动3</li>
<li>拖动4</li>
<li>拖动5</li>
<li>拖动6</li>
<li>拖动7</li>
<li>拖动8</li>
<li>拖动9</li>
<li>拖动10</li>
</ul>
</body>
JS:
<script> var flag; // 鼠标按下 var downX; // 鼠标点击的x下标 var scrollLeft; // 当前元素滚动条的偏移量 nav.addEventListener("mousedown", function (event) { flag = true; downX = event.clientX; // 获取到点击的x下标 scrollLeft = this.scrollLeft; // 获取当前元素滚动条的偏移量 }); nav.addEventListener("mousemove", function (event) { if (flag) { // 判断是否是鼠标按下滚动元素区域 // 获取移动的x轴 var moveX = event.clientX; // 当前移动的x轴下标减去刚点击下去的x轴下标得到鼠标滑动距离 var scrollX = moveX - downX; // 鼠标按下的滚动条偏移量减去当前鼠标的滑动距离 this.scrollLeft = scrollLeft - scrollX; console.log(scrollX) } }); // 鼠标抬起停止拖动 nav.addEventListener("mouseup", function () { flag = false; }); // 鼠标离开元素停止拖动 nav.addEventListener("mouseleave", function (event) { flag = false; }); </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。