<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #div1 {width:100px; height:100px; background:red; position:absolute;} div {width:3px; height:3px; position:absolute; background:black;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.onload=function () { var oDiv=document.getElementById('div1'); oDiv.onmousedown=function (ev) { var oEvent=ev||event; var disX=oEvent.clientX-oDiv.offsetLeft; var disY=oEvent.clientY-oDiv.offsetTop; document.onmousemove=function (ev) { var oEvent=ev||event; var l=oEvent.clientX-disX; var t=oEvent.clientY-disY; if(l <=0 ){ oDiv.style.left = 0 }else if(oEvent.clientX >= document.body.clientWidth){ oDiv.style.left = oEvent.clientX - oDiv.offsetWidth + 'px' }else{ oDiv.style.left=l+'px'; } if(t <=0 ){ oDiv.style.top = 0 }else if(oEvent.clientY >= document.body.clientHeight){ oDiv.style.top = oEvent.clientY - oDiv.offsetHeight + 'px' }else{ oDiv.style.top=t+'px'; } }; document.onmouseup=function () { document.onmousemove=null; document.onmouseup=null; }; }; }; </script> </head> <body> <div id="div1"> </div> </body> </html>