<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>title</title> <style> *{ margin: 0; padding: 0; } #box{ background: black; width: 100px; height: 100px; border-radius: 10px; cursor: pointer; position: relative; } </style> </head> <body> <div id="box"></div> <script> window.onload = function () { var box = document.getElementById('box'); var X = 0; var Y = 0; // 鼠标按下 box.onmousedown = function (ev) { var oEvent = ev || event; // 鼠标在BOX中的横向距离 = 鼠标位置 - div位置 X = oEvent.clientX - box.offsetLeft; // 鼠标在BOX中的纵向距离 = 鼠标位置 - div位置 Y = oEvent.clientY - box.offsetTop; // 鼠标移动 document.onmousemove = function (ev) { var oEvent = ev || event; box.style.left = oEvent.clientX - X + 'px'; box.style.top = oEvent.clientY - Y + 'px'; }; // 鼠标抬起,清除所有事件,否则还会移动 document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }; }; }; </script> </body> </html>