组件开发 : 多组对象,像兄弟之间的关系( 代码复用的一种形式 )
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 5 <title>拖拽组件开发</title> 6 <style type="text/css"> 7 #div1{width:100px;height:100px;background: #f00;position: absolute;} 8 #div2{width:100px;height:100px;background: orange;position: absolute;left:100px;} 9 #div3{width:100px;height:100px;background: green;position: absolute;left:200px;} 10 #div4{width:100px;height:100px;background: blue;position: absolute;left:300px;} 11 </style> 12 <script type="text/javascript"> 13 window.onload=function(){ 14 var d1 = new Drag(); 15 d1.init({ 16 id:"div1" 17 }); 18 19 var d2 = new Drag(); 20 d2.init({ 21 id:"div2", 22 toDown:function(){document.title = "哈哈"} 23 }); 24 25 var d3 = new Drag(); 26 d3.init({ 27 id:"div3", 28 toDown:function(){document.title = "爱奇艺"}, 29 toUp:function(){document.title = "蛋疼"} 30 }); 31 32 var d4 = new Drag(); 33 d4.init({ 34 id:"div4", 35 toUp:function(){document.title = "哎哟哟"} 36 }); 37 } 38 function Drag(){ 39 this.obj = null; 40 this.disX = 0; 41 this.disY = 0; 42 43 this.settings={ 44 toDown:function(){}, 45 toUp:function(){} 46 } 47 } 48 Drag.prototype.init=function(opt){ 49 var This = this; 50 this.obj = document.getElementById(opt.id); 51 52 extend(this.settings,opt); 53 this.obj.onmousedown=function(ev){ 54 var ev = ev || window.event; 55 This.fnDown(ev); 56 This.settings.toDown(); 57 document.onmousemove=function(ev){ 58 var ev = ev || window.event; 59 This.fnMove(ev); 60 } 61 document.onmouseup=function(){ 62 This.fnUp(); 63 This.settings.toUp(); 64 } 65 } 66 } 67 Drag.prototype.fnDown=function(ev){ 68 this.disX = ev.clientX-this.obj.offsetLeft; 69 this.disY = ev.clientY-this.obj.offsetTop; 70 } 71 Drag.prototype.fnMove=function(ev){ 72 this.obj.style.left = ev.clientX-this.disX+"px"; 73 this.obj.style.top = ev.clientY-this.disY+"px"; 74 } 75 Drag.prototype.fnUp=function(){ 76 document.onmousemove=null; 77 document.onmouseup=null; 78 } 79 80 function extend(obj1,obj2){ 81 for(var attr in obj2){ 82 obj1[attr] = obj2[attr]; 83 } 84 } 85 </script> 86 </head> 87 <body> 88 <div id="div1"></div> 89 <div id="div2"></div> 90 <div id="div3"></div> 91 <div id="div4"></div> 92 </body> 93 </html>