拖拽
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>拖拽</title> <style> *{ margin: 0px; padding: 0px; } #parent{ width: 100px; height: 100px; background: red; position: absolute; top: 0px; left: 0px; } #son{ width: 100px; height: 100px; background: #ace; position: absolute; top: 0px; left: 100px; } </style> </head> <body> <div id="parent"></div> <div id="son"></div> <script type="text/javascript"> window.onload = function(){ var t1 = new Drag("parent"); t1.init(); var t2 = new Dragextend("son"); t2.init(); } function Drag(id){ this.oBox = document.getElementById(id); this.disX = 0; this.disY =0; } Drag.prototype.init = function(){ var _this = this; this.oBox.onmousedown = function(ev){ var ev = ev||event; _this.Down(ev); document.onmousemove = function(ev){ var ev = ev||event; _this.Move(ev); }; document.onmouseup = function(){ _this.Up(); } return false; } }; Drag.prototype.Down = function(ev){ this.disX = ev.clientX - this.oBox.offsetLeft; this.disY = ev.clientY - this.oBox.offsetTop; }; Drag.prototype.Move =function(ev){ this.oBox.style.left = ev.clientX - this.disX +'px'; this.oBox.style.top = ev.clientY - this.disY + 'px'; }; Drag.prototype.Up = function(){ document.onmousemove = null; document.onmouseup = null; }; function Dragextend(id){ Drag.call(this,id); } extend(Dragextend.prototype,Drag.prototype); Dragextend.prototype.Move = function(ev){ var L = ev.clientX - this.disX; var T = ev.clientY - this.disY; if(L < 0){ L = 0; } if(L >= document.documentElement.clientWidth - this.oBox.offsetWidth){ L = document.documentElement.clientWidth - this.oBox.offsetWidth; } if(T < 0){ T = 0; } if(T>=document.documentElement.clientHeight - this.oBox.offsetHeight){ T = document.documentElement.clientHeight - this.oBox.offsetHeight; } this.oBox.style.left = L +'px'; this.oBox.style.top = T + 'px'; } function extend(obj1,obj2){ for(var attr in obj2){ obj1[attr] = obj2[attr]; } } </script> </body> </html>