<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box {100px; height:100px; background:red;position:absolute;} </style> </head> <body> <div id="box"> </div> <script type="text/javascript"> var box = document.getElementById('box'); //定义全局变量 var divX = 0; //div的x坐标 var divY = 0; //div的y坐标 var mouseX = 0; //鼠标的x坐标 var mouseY = 0; //属性的y坐标 var sw = false; //表示开关 //绑定mouserdown事件 box.onmousedown = function(evt){ var e = evt || window.event; console.log(e); //获取div的位置 divX = this.offsetLeft; //值是没有单位的 divY = this.offsetTop; //获取鼠标所处的位置 mouseX = e.clientX; mouseY = e.clientY; //开启开关 sw = true; } //绑定mousemove事件 document.onmousemove = function(evt){ var e = evt || window.event; //只有开启了开关,才有效 if (sw) { var disX = e.clientX - mouseX; var disY = e.clientY - mouseY; //console.log(disX,disY); //利用相对论,设置div的left和top值就可以了 box.style.left = divX + disX + "px"; //注意加单位 box.style.top = divY + disY + "px"; } } //绑定mouseup事件 document.onmouseup = function(){ sw = false; } </script> </body> </html>