js实现拖动盒子查看内容 内容拖动
2024-01-08 16:27:19
?
一.分析实现过程
1.鼠标拖动的操作是,按下鼠标不松,拖动鼠标,就需要监听鼠标点击事件(onmousedown),鼠标拖动事件(onmousemove)
2.鼠标拖动事件的监听时机,是在按下鼠标之后监听的,所以鼠标拖动事件需要放在鼠标按下事件(onmousedown)中
3.获取鼠标点击的位置A在外层盒子中可视区域x轴位置(clientX)及x轴滚动条位置B(scrollLeft)
4.在外层盒子中鼠标点击盒子的位置拖动的时候获取可视区域x轴位置C减去一开始点击的位置A,之后用位置B减去,C减A的值,这就是最终盒子需要跟随鼠标所拖动的位置
5.鼠标抬起释放事件
?
二.实现代码????????
<style> .outBox{ width:300px; height:200px; background: blanchedalmond; overflow: hidden; margin:20px auto; } .innerBox{ width: 600px; height: 200px; cursor: grab; } </style> <body> <div class="outBox"> <div class="innerBox"> <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis nam id neque cupiditate a, nihil corporis aut officiis nesciunt, incidunt consequuntur acc usamus, iusto architecto nemo? Aspernatur omnis soluta molestiae excepturi!</span> <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis nam id neque cupiditate a, nihil corporis aut officiis nesciunt, incidunt consequuntur acc usamus, iusto architecto nemo? Aspernatur omnis soluta molestiae excepturi!</span> <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis nam id neque cupiditate a, nihil corporis aut officiis nesciunt, incidunt consequuntur acc usamus, iusto architecto nemo? Aspernatur omnis soluta molestiae excepturi!</span> <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis nam id neque cupiditate a, nihil corporis aut officiis nesciunt, incidunt consequuntur acc usamus, iusto architecto nemo? Aspernatur omnis soluta molestiae excepturi!</span> <span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis nam id neque cupiditate a, nihil corporis aut officiis nesciunt, incidunt consequuntur acc usamus, iusto architecto nemo? Aspernatur omnis soluta molestiae excepturi!</span> </div> </div> <script> let wrapperBox= document.querySelector('.outBox') let innerBox=document.querySelector('.innerBox') wrapperBox.onmousedown=function(e){ let startX=e.clientX; let originalScrollX=wrapperBox.scrollLeft; document.onmousemove=function(e){ let subs=e.clientX-startX; wrapperBox.scrollLeft= originalScrollX-subs; } //鼠标抬起释放事件 document.onmouseup=function(){ document.onmousemove=document.onmouseup=null; } } </script> </body>
文章来源:https://blog.csdn.net/qq_41429765/article/details/130527922
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!