<!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" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } #div1{ width: 100px; height: 100px; background-color: #eee; position: absolute; left: 0; top: 0; } </style> <script> window.onload=function(){ var oDiv = document.getElementById('div1'); var disX = disY =0; oDiv.onmousedown=function(ev){ var oEvent = ev||event; var scrollTop = document.documentElement.scrollTop||document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft||document.body.scrollLeft; // var x = oEvent.clientX+scrollLeft-oDiv.offserLeft; // var y = oEvent.clientY+scrollTop-oDiv.offserTop; disX = oEvent.clientX-oDiv.offsetLeft; 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){ l=0; }else if(l>document.documentElement.clientWidth-oDiv.offsetWidth){ l=document.documentElement.clientWidth-oDiv.offsetWidth; } if(t<0){ t=0; }else if(t>document.documentElement.clientHeight-oDiv.offsetHeight){ t=document.documentElement.clientHeight-oDiv.offsetHeight; } oDiv.style.left=l+'px'; oDiv.style.top=t+'px'; }; document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; }; return false; }; } </script> </head> <body> <div id="div1"></div> </body> </html>
限制了用户上下左右拖出可视区,但是还有onresize这个方面有待优化。用户改变浏览器窗口大小的时候。