首先来了解一下,面向对象练习的基本规则和问题:
先写出普通的写法,然后改成面向对象写法项 普通方法变形
·尽量不要出现函数嵌套函数 ·可以有全局变量 ·把onload函数中不是赋值的语句放到单独函数中
改成面向对象
·全局变量就是属性 ·函数就是方法 ·onload中创建对象 ·改this指针问题
先把拖拽效果的布局完善好: HTML结构:
Box">
csc样式: #Box{position: absolute;width: 200px;height: 200px;background: red;}
第一步,首先把面向过程的拖拽回顾一下
代码如下:
获取元素和初始值
var oBox = document.getElementById('Box'),
disX = 0,disY = 0;
// 容器鼠标按下事件
oBox.onmousedown = function (e){
var e = e || window.event;
disX = e.clientX - this.offsetLeft;
disY = e.clientY - this.offsetTop;
document.onmousemove = function (e){
var e = e || window.event;
oBox.style.left = (e.clientX - disX) + 'px';
oBox.style.top = (e.clientY - disY) + 'px';
};
document.onmouseup = function (){
document.onmousemove = null;
document.onmouseup = null;
};
return false;
};
};
第二步,把面向过程改写为面向对象
代码如下:
Box');
drag.init();
};
// 构造函数Drag
function Drag(id){
this.obj = document.getElementById(id);
this.disX = 0;
this.disY = 0;
}
Drag.prototype.init = function (){
// this指针
var me = this;
this.obj.onmousedown = function (e){
var e = e || event;
me.mouseDown(e);
// 阻止默认事件
return false;
};
};
Drag.prototype.mouseDown = function (e){
// this指针
var me = this;
this.disX = e.clientX - this.obj.offsetLeft;
this.disY = e.clientY - this.obj.offsetTop;
document.onmousemove = function (e){
var e = e || window.event;
me.mouseMove(e);
};
document.onmouseup = function (){
me.mouseUp();
}
};
Drag.prototype.mouseMove = function (e){
this.obj.style.left = (e.clientX - this.disX) + 'px';
this.obj.style.top = (e.clientY - this.disY) + 'px';
};
Drag.prototype.mouseUp = function (){
document.onmousemove = null;
document.onmouseup = null;
};
第三步,看看代码有哪些不一样
代码如下:
函数Drag
function Drag(id){
this.obj = document.getElementById(id);
this.disX = 0;
this.disY = 0;
}
然后就是把函数都写在原型上面:
代码如下: