起首来相识一下,面向对象演习的基础划定规矩和题目:
先写出一般的写法,然后改成面向对象写法项
- 一般要领变形
·只管不要涌现函数嵌套函数
·能够有全局变量
·把onload函数中不是赋值的语句放到零丁函数中 - 改成面向对象
·全局变量就是属性
·函数就是要领
·onload中建立对象
·改this指针题目
先把拖拽结果的规划完美好:HTML
组织:<div id="box"></div>
csc
款式:#box{position: absolute;width: 200px;height: 200px;background: red;}
第一步,起首把面向历程的拖拽回忆一下
window.onload = function (){
// 猎取元素和初始值
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;
};
};
第二步,把面向历程改写为面向对象
window.onload = function (){
var drag = new Drag('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;
}
恪守前面的写好的划定规矩,把全局变量都变成属性!
然后就是把函数都写在原型上面:
Drag.prototype.init = function (){
};
Drag.prototype.mouseDown = function (){
};
Drag.prototype.mouseMove = function (){
};
Drag.prototype.mouseUp = function (){
};
先来看看init
函数:
Drag.prototype.init = function (){
// this指针
var me = this;
this.obj.onmousedown = function (e){
var e = e || event;
me.mouseDown(e);
// 阻挠默许事宜
return false;
};
};
我们运用me变量来保留了this
指针,为了背面的代码不涌现this
指向的毛病
接着是mouseDown
函数:
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();
}
};
改写成面向对象的时刻要注意一下event对象
。由于event对象
只涌现在事宜中,所以我们要把event对象
保留变量,然后经由过程参数通报!
背面的mouseMove
函数和mouseUp
函数就没什么要注意的处所了!
要注意的题目
关于this
指针的题目,面向对象内里this
迥殊主要!
this拓展浏览:
http://div.io/topic/809
关于event对象
的题目,event对象
只涌现在事宜内里,所以写要领的时刻要注意一下!