本文最后更新于:几秒前
实现的效果如图
实现步骤:
- 鼠标按下时进入拖拽状态
onmousedown
- 鼠标移动时,如果是拖拽状态,则元素跟随移动
onmousemove
- 鼠标弹起或鼠标离开元素范围时退出拖拽状态
onmouseup
和onmouseleave
如何跟随移动?计算两个鼠标指针的距离差,然后应用到目标元素上
需要注意的是(我没做的):
- 若是对鼠标点击有要求,需要判断是否为左键
- 若是对移动范围有要求,需要做相应处理禁止移动
- 若是对性能有要求,记得做防抖处理
简单的实现拖拽代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>拖拽移动元素</title> <style> #tools { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); height: 100px; width: 100px; background-color: cadetblue; cursor: move; } </style> </head> <body> <div id="tools"></div> <script> let start = null; let isDrag = false; const tools = document.getElementById("tools"); tools.onmousedown = function (e) { start = { x: e.x, y: e.y, }; isDrag = true; } tools.onmouseup = function (e) { isDrag = false; } tools.onmouseleave = function (e) { isDrag = false; } tools.onmousemove = function (e) { if (isDrag) { let distance = { x: e.x - start.x, y: e.y - start.y, } tools.style.left = tools.offsetLeft + distance.x + 'px'; tools.style.top = tools.offsetTop + distance.y + 'px'; start.x = e.x; start.y = e.y; } } </script> </body> </html>
|