HTML部分
<div id="div1"></div> <div id="div2"></div>
CSS部分
<style> #div1{ 100px;height: 100px;background-color: red;position: absolute;} #div2{ 100px;height: 100px;background-color: blue;position: absolute;left:100px;} </style>
普通JS写法
//普通写法 function Drag(id){ var obj = document.getElementById(id); var disX = 0; var disY = 0; obj.onmousedown = function(ev){ var ev = ev || window.event; disX = ev.clientX - obj.offsetLeft; disY = ev.clientY - obj.offsetTop; document.onmousemove = function(ev){ var ev = ev || window.event; obj.style.left = ev.clientX - disX + "px"; obj.style.top = ev.clientY - disY + "px"; } document.onmouseup = function(){ document.onmouseup = document.onmousemove = null; } } } window.onload = function(){ Drag("div1"); Drag("div2"); }
面向对象的写法:
function Drag(id){ this.obj = document.getElementById(id); this.disX = 0; this.disY = 0; } Drag.prototype.init = function(){ var that = this; this.obj.onmousedown = function(ev) { var ev = ev || window.event; that.fnDown(ev); document.onmousemove = function (ev) { var ev = ev || window.event; that.fnMove(ev); } document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } } return false; } Drag.prototype.fnDown = function(ev){ this.disX = ev.clientX - this.obj.offsetLeft; this.disY = ev.clientY - this.obj.offsetTop; }; Drag.prototype.fnMove = function(ev){ this.obj.style.left = ev.clientX - this.disX + 'px'; this.obj.style.top = ev.clientY - this.disY + 'px'; };
//继承父类的子组件 function childDrag(id){ Drag.call(this,id); }
function extend(obj1,obj2){ for(var attr in obj2) { obj1[attr] = obj2[attr]; } } extend(childDrag.prototype,Drag.prototype);
//重新定义fnMove函数 childDrag.prototype.fnMove = function(ev){ var L = ev.clientX - this.disX; var T = ev.clientY - this.disY; if(L<0){ L = 0; }else if(L>document.documentElement.clientWidth - this.obj.offsetWidth){ L = document.documentElement.clientWidth - this.obj.offsetWidth; } if(T<0){ T = 0; }else if(T>document.documentElement.clientHeight - this.obj.offsetHeight){ T = document.documentElement.clientHeight - this.obj.offsetHeight; } this.obj.style.left = L + 'px'; this.obj.style.top = T + 'px'; }; window.onload = function(){ var obj = new Drag("div1"); obj.init(); var obj2 = new childDrag("div2"); obj2.init(); }