欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

javascript 类对象的应用

程序员文章站 2022-05-03 07:58:18
类对象继承的实现 先创建一个父级对象Drag   /**  * @author zhaoshaobang  */ function D...

类对象继承的实现

先创建一个父级对象Drag

 

/**
 * @author zhaoshaobang
 */
function Drag(id){
	var _this=this;
	this.oDiv=document.getElementById(id);
	this.disX=0;
	this.disY=0;
	this.oDiv.onmousedown=function(evt)
	{
		_this.downFn(evt);
	};
};
Drag.prototype.downFn=function(evt){
	var e=evt||event;
	var _this=this;
	this.disX=e.clientX-this.oDiv.offsetLeft;
	this.disY=e.clientY-this.oDiv.offsetTop;
	document.onmousemove=function(evt){
		_this.moveFn(evt);
	};
	
	document.onmouseup=function(evt){
		_this.upFn(evt);
	};
};
Drag.prototype.moveFn=function(evt){
	var e=evt||event;
	
	this.oDiv.style.left=e.clientX-this.disX+'px';
	this.oDiv.style.top=e.clientY-this.disY+'px';
		
};
Drag.prototype.upFn=function(){
	document.onmousemove=null;
	document.onmouseup=null;
};

在创建一个子集对象,并设置拖拽范围

 

 

/**
 * @author zhaoshaobang
 */

//继承属性

function LimitDrag(id)
{
	Drag.call(this,id);//Drag中的this会变为LimitDrag
}
//  继承父级方法
for(var i in Drag.prototype)
{
	LimitDrag.prototype[i]=Drag.prototype[i];
}

LimitDrag.prototype.moveFn=function(evt){
	var e=evt||event;
	var i=e.clientX-this.disX;
	
	if(i<0)
	{
		i=0;
	}
	else if(i>document.documentElement.clientWidth-this.oDiv.offsetWidth)
	{
		i=document.documentElement.clientWidth-this.oDiv.offsetWidth;
	}
	this.oDiv.style.left=i+'px';
	this.oDiv.style.top=e.clientY-this.disY+'px';
};

运行结果如下图

 

javascript 类对象的应用