🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 拖拽的实现 主要用到offsetX,offsetY,pageX,pageY,document.documentElement.clientWidth,document.documentElement.clientHeight ~~~ <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" media="screen" href="main.css" /> <script src="main.js"></script> <style> html, body { height: 100%; width: 100%; padding: 0; margin: 0; } #father { position: relative; height: 100%; width: 100%; } #son { height: 100px; width: 100px; background-color: green; position: absolute; } </style> </head> <body> <div id="father"> <div id="son"></div> </div> </body> <script> (function () { var father = document.getElementById('father') var son = document.getElementById('son') var dragging = false; var positionSonX, positionSonY, mouseX, mouseY, offsetX, offsetY; son.onmousedown = down; document.onmousemove = move; document.onmouseup = leave; function down(e) { dragging = true; positionSonX = son.offsetLeft; // son相对于father的left positionSonY = son.offsetTop; // son相对于father的top mouseX = parseInt(getMouseXY(e).x); // 获取鼠标当前的位置X坐标 mouseY = parseInt(getMouseXY(e).y); // 获取鼠标当前的位置Y坐标 offsetX = mouseX - positionSonX; // 计算得到偏移量 offsetY = mouseY - positionSonY; // 计算得到偏移量 } function move(e) { if (dragging) { var x = getMouseXY(e).x - offsetX; var y = getMouseXY(e).y - offsetY; var width = document.documentElement.clientWidth - son.offsetWidth; var height = document.documentElement.clientHeight - son.offsetHeight; x = Math.min(Math.max(0, x), width); y = Math.min(Math.max(0, y), height); son.style.left = x + 'px'; son.style.top = y + 'px'; } } function leave() { dragging = false; } function getMouseXY(e) { var x = 0, y = 0; e = e || window.event; if (e.pageX) { x = e.pageX; y = e.pageY; } return { x, y } } })() </script> </html> ~~~