<style>
#div1{width: 200px;height: 200px; background: red; position: absolute;}
#div2{width: 200px;height: 200px; background: green; position: absolute;}
</style>
//父类
<script src="Drag.js"></script>
function Drag(id){//构造函数
var _this=this;
this.disX=0;
this.disY=0;
this.oDiv=document.getElementById(id);
this.oDiv.onmousedown=function(ev){
_this.fnDown(ev);
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(ev){
_this.fnMove(ev);
};
document.onmouseup=function(){
_this.fnUp();
};
}
Drag.prototype.fnMove=function(ev){//鼠标移动处理方法
var oEvent =ev||event;
this.oDiv.style.left=oEvent.clientX-this.disX+"px";
this.oDiv.style.top=oEvent.clientY-this.disY+"px";
};
Drag.prototype.fnUp=function(){//鼠标松开处理方法
document.onmousemove=null;
document.onmouseup=null;
}
//子类
<script src="LimitDrag.js"></script>
function LimitDrag(id){
Drag.call(this,id);//call 方法可以用来代替另一个对象调用一个方法
}
for(var i in Drag.prototype){
LimitDrag.prototype[i]=Drag.prototype[i];//将父类复制一份到子类
}
LimitDrag.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){
t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
}
this.oDiv.style.left=l+"px";
this.oDiv.style.top=t+"px";
};
<script>
//自动加载
window.onload=function(){
new Drag("div1");
new LimitDrag('div2');
};
</script>
<div id="div1">普通拖拽</div>
<div id="div2">限制范围</div>
上一篇:
js使用cookie基本操作
下一篇:
js实现ajax读取服务器端数据
友情提示:垃圾评论一律封号...