1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| <!DOCTYPE HTML> <html> <head> <meta charset='utf-8'> <title></title> <style type="text/css"> *{ margin:0; padding:0;} .drag{ width:100px; height: 100px; background:red; position: absolute;} </style> <script type="text/javascript" src='jquery-1.11.1.min.js'></script> <script type="text/javascript"> window.onload=function(){ var dg=new Drag('drag'); }; function Drag(obj){ this.oDiv=document.getElementById(obj); this.x=0; this.y=0; var _this=this; this.oDiv.onmousedown=function(ev){ _this.cc(ev); return false; }; }; Drag.prototype.cc=function(ev){ var oEvent=ev||event; var _this=this; this.x=oEvent.clientX-this.oDiv.offsetLeft; this.y=oEvent.clientY-this.oDiv.offsetTop; document.onmousemove=function(ev){ _this.aa(ev); }; document.onmouseup=function(){ _this.bb(); }; }; Drag.prototype.aa=function(ev){ var oEvent=ev||event; var outX=oEvent.clientX-this.x; var outY=oEvent.clientY-this.y; if (outX<=0) { outX=0; }else if(outX>document.documentElement.clientWidth-this.oDiv.offsetWidth){ outX=document.documentElement.clientWidth-this.oDiv.offsetWidth; }; if (outY<=0) { outY=0; }else if(outY>document.documentElement.clientHeight-this.oDiv.offsetHeight){ outY=document.documentElement.clientHeight-this.oDiv.offsetHeight; };
this.oDiv.style.left=outX+'px'; this.oDiv.style.top=outY+'px'; }; Drag.prototype.bb=function(ev){ document.onmousemove=null; document.onmouseout=null; }; </script> </head> <body> <div class="drag" id='drag'></div> </body> </html>
|