Js使用面向对象和面向过程的方法实现拖拽物体的效果
1.面向过程的拖拽实现代码:
<!DOCTYPE html> <html> <head> <title>drag Div</title> <style type="text/css"> #div1{width: 100px;height: 100px;background: red;position: absolute;} </style> <script type="text/javascript"> window.onload=function(){ var oDiv=document.getElementById('div1'); var disX=0; var disY=0; oDiv.onmousedown=function(ev){ var oEvent=ev||event; 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){ l=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>
2.面向对象的实现方法,只用新建对象,可以实现多个div的拖拽运动
<!DOCTYPE html> <html> <head> <title>drag Div</title> <style type="text/css"> #div1{width: 100px;height: 100px;background: red;position: absolute;} #div2{width: 100px;height: 100px;background: yellow;position: absolute;} </style> <script type="text/javascript"> window.onload=function(){ new Drag('div1'); new Drag('div2'); } function Drag(id){ var _this=this; this.disX=0; this.dixY=0; this.oDiv=document.getElementById(id); this.oDiv.onmousedown=function() { _this.fnDown(); }; return false; } Drag.prototype.fnDown=function(ev){ var _this=this; var oEvent=ev||event; this.disX=oEvent.clientX-this.oDiv.offsetLeft; this.disY=oEvent.clientY-this.oDiv.offsetTop; document.onmousemove=function(){ _this.fnMove(); }; document.onmouseup=function(){ _this.fnUp(); }; }; Drag.prototype.fnMove=function(ev){ var oEvent=ev||event; var l=oEvent.clientX-this.disX; var t=oEvent.clientY-this.disY; if (l<0) {l=0;} else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){ l=document.documentElement.clientWidth-this.oDiv.offsetWidth; } if (t<0) {t=0;} else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight){ l=document.documentElement.clientHeight-this.oDiv.offsetHeight; } this.oDiv.style.left=l+'px'; this.oDiv.style.top=t+'px'; }; Drag.prototype.fnUp=function(){ document.onmousemove=null; document.onmouseup=null; }; </script> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> </html>