面向对象拖拽与继承
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>无标题文档</title> 6 <style> 7 #box{width:100px;height:100px;background:#f00;position:absolute;} 8 #box2{width:100px;height:100px;background:#000;position:absolute;} 9 </style> 10 <script> 11 window.onload=function() 12 { 13 new drag('box'); 14 new LimitDrag('box2'); 15 }; 16 function drag(id) 17 { 18 var _this=this; 19 this.disX = 0; 20 this.disY = 0; 21 this.oBox = document.getElementById(id); 22 this.oBox.onmousedown=function(ev) 23 { 24 _this.fnDown(ev); 25 }; 26 }; 27 drag.prototype.fnDown=function(ev) 28 { 29 var ev = ev||event; 30 var _this = this; 31 this.disX = ev.clientX - this.oBox.offsetLeft; 32 this.disY = ev.clientY - this.oBox.offsetTop; 33 document.onmousemove=function(ev) 34 { 35 _this.fnMove(ev); 36 }; 37 document.onmouseup=function() 38 { 39 _this.fnUp(); 40 }; 41 return false; 42 }; 43 44 drag.prototype.fnMove=function(ev) 45 { 46 var ev = ev||event; 47 this.oBox.style.left=ev.clientX - this.disX+'px'; 48 this.oBox.style.top=ev.clientY - this.disY+'px'; 49 }; 50 drag.prototype.fnUp=function() 51 { 52 document.onmouseup=null; 53 document.onmousemove=null; 54 }; 55 function LimitDrag(id) 56 { 57 drag.call(this,id); 58 }; 59 for(i in drag.prototype) 60 { 61 LimitDrag.prototype[i]=drag.prototype[i]; 62 }; 63 LimitDrag.prototype.fnMove=function(ev) 64 { 65 var ev = ev||event; 66 var l = ev.clientX - this.disX; 67 var t = ev.clientY - this.disY; 68 if(l<0){l=0} 69 else if(l>document.documentElement.clientWidth-this.oBox.offsetWidth){l=document.documentElement.clientWidth-this.oBox.offsetWidth;} 70 if(t<0){t=0} 71 else if(t>document.documentElement.clientHeight-this.oBox.offsetHeight){t=document.documentElement.clientHeight-this.oBox.offsetHeight}; 72 this.oBox.style.left=l+'px'; 73 this.oBox.style.top=t+'px'; 74 }; 75 </script> 76 </head> 77 78 <body> 79 <div id="box"></div> 80 <div id="box2"></div> 81 </body> 82 </html>