Javascript 面向对象编程之拖拉

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{ width:200px; height:200px; background:yellow; position:absolute; z-index:555;}
#div2{ width:200px; height:200px; background:green; position:absolute;}
</style>
<script>

window.onload=function(){
new Drag("div1");//拖拉构造函数对象
new LimitDrag("div2");//继承Drag对象方法,属性

}

function Drag(id)
{
var _this=this;//子涵数引用对象
this.disX=0;//设置变量
this.disY=0;
this.oDiv=document.getElementById(id);
this.oDiv.onmousedown=function(ev){//点击执行涵数FnDown/
//console.log(_this);
_this.fnDown(ev);
return false;

}
}

Drag.prototype.fnDown=function(ev)
{

var _this=this;
var oEvent=ev||event;//兼容IE的鼠标坐标
this.disX=oEvent.clientX-this.oDiv.offsetLeft;//鼠标点击位置到div左边的距离
this.disY=oEvent.clientY-this.oDiv.offsetTop;//鼠标点击位置到div顶边的距离
//console.log(this.disX+":"+this.disY);
document.onmousemove=function(ev)//移动时执行涵数
{
_this.fnMove(ev);
}
document.onmouseup=function(ev)//放松时执行涵数
{
_this.fnUp(ev);
}
}

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.disX+"PX"
}
Drag.prototype.fnUp=function()
{
document.onmousemove=null;
document.onmouseup=null;
}


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;//获取left边距离
var t=oEvent.clientY-this.disY;//获取top边距离
if(l<0)
{
l=0;
}
else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth)
{
l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
}
this.oDiv.style.left=l+"px";
this.oDiv.style.top=t+"px";
}
</script>
</head>

<body>
<div id="div1"></div>
<div id="div2"></div>

</body>
</html>

posted @ 2014-09-25 16:03  随波逐流196  阅读(171)  评论(0编辑  收藏  举报