鼠标事件与滚动条的结合 该方法主要解决的是有横向滚动条的元素,滚动条太小,要左右移动太难,所以使用js事件进行处理,直接对元素拖动就能左右移动滚动条,但是又不想使用拖拽事件。 主要事件: onmousedown 鼠标点击 onmousemove 鼠标移动 onmouseout 鼠标移出 onmouseup 鼠标松开 效果图: 代码块: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>使用鼠标事件完成类似于拖拽的功能</title> <style type="text/css"> p{ text-align: center; margin-top: 60px; } #father-box { width: 600px; height: 600px; border: 1px solid black; overflow: auto; margin: 0 auto; } #son-box { width: 800px; height: 800px; line-height: 800px; text-align: center; user-select:none; } </style> </head> <body> <p id="p1">默认状态</p> <p id="p2" style="display:none;">移动后的状态——只使用鼠标拖动,未拖动滚动条</p> <div id="father-box" onmousedown="mousedownFun(event)" onmousemove="mousemoveFun(event)" onmouseout="mouseoutFun(event)" onmouseup="mouseupFun(event)"> <div id="son-box"> 这只是一些文字,用来看的 </div> </div> <script> let isMove = false; // 判断鼠标按下或是抬起状态 let defX = 0; // 初始的X位置 let defY = 0; // 初始的Y位置 let stateX = 0; // 开始拖动的X let stateY = 0; // 开始拖动的Y let moveX = 0; // 拖动的X距离 let moveY = 0; // 拖动的Y距离 // 鼠标按下——准备开始拖拽 function mousedownFun(event) { let fatherBox = document.getElementById('father-box'); isMove = true; defX = fatherBox.scrollLeft; defY = fatherBox.scrollTop; stateX = event.x; stateY = event.y; } // 鼠标移动——正在拖拽 function mousemoveFun(event) { let fatherBox = document.getElementById('father-box'); let p1 = document.getElementById('p1'); let p2 = document.getElementById('p2'); if (isMove) { moveX = stateX - event.x; moveY = stateY - event.y; fatherBox.scrollLeft = defX + moveX; fatherBox.scrollTop = defY + moveY; p1.style.display = 'none' p2.style.display = 'block' } } // 鼠标移出——不在对象内,结束拖动 function mouseoutFun(event) { mouseupFun() } // 鼠标松开——结束拖拽 function mouseupFun(event) { isMove = false; defX = event.x; defY = event.y; } </script> </body> </html> |
|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )
GMT+8, 2024-12-23 23:30 , Processed in 0.022406 second(s), 17 queries .
Powered by Mxzdjyxk! X3.5
© 2001-2024 Discuz! Team.