JavaScript 面向对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#div1 {width:100px; height:100px; background:red; position:absolute;}
#div2 {width:100px; height:100px; background:yellow; position:absolute;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload=function()
{
	new Drag('div1');	
	
	new Drag('div2'); 
}

function Drag(id)
{	
	var _this=this;
	this. disX=0;
	this.disY=0;
	this.oDiv=document.getElementById(id);
	
	this.oDiv.onmousedown=function()
	{
		_this.fnDown();
	};
};

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(){
		_this.fnMove();
	};
	
	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>
</head>

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

猜你喜欢

转载自blog.csdn.net/qq_37995109/article/details/85214868