js面向对象编程之拖拽案例

责编:menVScode 2017-06-19 16:19 阅读(1060)

普通方法变型:

        尽量不要出现函数嵌套函数

        可以有全局变量

        把onload中不是赋值的语句放到单独函数中

改成面向对象:

        全局变量就是属性

        函数就是方法

        Onload中创建对象

        改this指向问题

        html,css部分

<style>
	#box{width: 120px;height: 120px;background: #000;position: absolute;}
</style>
<body>
	<div id="box"></div>
</body>

        传统的面向过程

window.onload = function(){
	var oBox = document.getElementById('box');
	var disY = 0;
	var disX = 0;
	oBox.onmousedown = function(ev){
		var ev = ev || window.event;
		disX = ev.clientX - oBox.offsetLeft;
		disY = ev.clientY - oBox.offsetTop;

		document.onmousemove = function(ev){
			var ev = ev || window.event;
			oBox.style.left = ev.clientX - disX + 'px';
			oBox.style.top = ev.clientY - disY + 'px';
		};
		
		document.onmouseup = function(){
			document.onmousemove = null;
			document.onmouseup = null;
		};
		return false;
	}	
}

        变型

window.onload = function(){
	oBox = document.getElementById('box');
	init();
}
var oBox = null;
var disY = 0;
var disX = 0;

function init(){
	oBox.onmousedown = doDown;
}

function doDown(ev){
	var ev = ev || window.event;
	disX = ev.clientX - oBox.offsetLeft;
	disY = ev.clientY - oBox.offsetTop;
	
	document.onmousemove = doMove;
	document.onmouseup = doUp;

	return false;
}

function doMove(ev){
	var ev = ev || window.event;
	oBox.style.left = ev.clientX - disX + 'px';
	oBox.style.top = ev.clientY - disY + 'px';
}

function doUp(){
	document.onmousemove = null;
	document.onmouseup = null;
}

        面向对象

window.onload = function(){
	var dragcage = new Drag('box');
	dragcage.init();
}

function Drag(id){
	this.oBox = document.getElementById(id);
	this.disY = 0;
	this.disX = 0;
}

Drag.prototype.init = function(){
	var _this = this;
	this.oBox.onmousedown = function(ev){

		var ev = ev || window.event;
		_this.doDown(ev);
		return false;
	}
}

Drag.prototype.doDown = function(ev){
	var _this = this;
	this.disX = ev.clientX - this.oBox.offsetLeft;
	this.disY = ev.clientY - this.oBox.offsetTop;
	
	document.onmousemove = function(ev){
		var ev = ev || window.event;
		_this.doMove(ev);
	}
	document.onmouseup = function(){
		_this.doUp();
	}
}

Drag.prototype.doMove = function(ev){
	this.oBox.style.left = ev.clientX - this.disX + 'px';
	this.oBox.style.top = ev.clientY - this.disY + 'px';
}

Drag.prototype.doUp = function(){
	document.onmousemove = null;
	document.onmouseup = null;
}
标签: js 面向对象 拖拽
前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码