首先來了解一下,面向對象練習的基本規則和問題:函數
先寫出普通的寫法,而後改爲面向對象寫法項佈局
先把拖拽效果的佈局完善好:HTML
結構:<div id="box"></div>
this
csc
樣式:#box{position: absolute;width: 200px;height: 200px;background: red;}
prototype
第一步,首先把面向過程的拖拽回顧一下指針
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; }; };
第二步,把面向過程改寫爲面向對象code
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; }
遵照前面的寫好的規則,把全局變量都變成屬性!get
而後就是把函數都寫在原型上面:原型
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對象
只出如今事件裏面,因此寫方法的時候要注意一下!