1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> #div1{ 100px; height: 100px; background-color: red; position: absolute;}</style> 7 <script> 8 9 window.onload=function(){ 10 var oDiv=document.getElementById("div1"); 11 oDiv.onmousedown=function(ev){ 12 var e=ev||window.event; 13 var offsetX=e.clientX-oDiv.offsetLeft;//获取鼠标离当前拖拽图片的左上角的距离 14 var offsetY=e.clientY-oDiv.offsetTop; 15 document.onmousemove=function(ev){ 16 var e=ev||window.event; 17 oDiv.style.left=e.clientX-offsetX+"px";//获取图片偏移距离 18 oDiv.style.top=e.clientY-offsetY+"px"; 19 } 20 } 21 document.onmouseup=function(){ 22 document.onmousemove=null;//清除鼠标移动 23 } 24 } 25 26 </script> 27 </head> 28 <body> 29 <div id="div1"></div> 30 </body> 31 </html>