DIV CSS 佈局教程網

JavaScript 拖拽物件導向改寫:原型繼承與 this 指向重點整理
編輯:關於JavaScript     

本文整理自己實作拖拽功能時,以原型方式封裝所延伸出的幾個關鍵問題,並附上可拖曳、可限制範圍的完整範例。

三個最容易踩到的觀念

  1. this 到底指向誰:一定要先確認當下的執行上下文,否則事件回呼裡的 this 會變成觸發事件的元素而非物件本身,實務上通常做法是先在建構式中存一份 var _this = this。
  2. call() 的用法:LimitDrag 要繼承 Drag 的屬性,用 Drag.call(this, id) 把建構流程套到子類別的 this 上。
  3. 兩種原型繼承的差別:這是本文最想強調的一點。
 for(var i in Drag.prototype) {
  LimitDrag.prototype[i] = Drag.prototype[i];   // 逐個複製:子類別日後修改不會影響父類別
}
LimitDrag.prototype = Drag.prototype;           // 直接指向同一個原型:子類別一改,父類別跟著變

換句話說,若打算在子類別裡覆寫 fnMove 卻不希望污染父類別,就必須用 for-in 逐個拷貝。

完整程式碼

 <html>
<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 LimitDrag('div2');
}
function Drag(id) {
  var _this=this;
  this.disx=0;
  this.disy=0;
  this.oDiv=document.getElementById(id);
  this.oDiv.onmousedown=function(ev){
    _this.fnDown(ev);
    return false;
  }
};
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(ev){ _this.fnMove(ev); }
  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;
};
function LimitDrag(id) {
  Drag.call(this,id);
}
for(var i in Drag.prototype) {
  LimitDrag.prototype[i]=Drag.prototype[i];
}
LimitDrag.prototype.fnMove=function(ev) {
  var oEvent=ev||event;
  var l=oEvent.clientX-this.disx;
  var t=oEvent.clientY-this.disy;
  if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth) {
    l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
  } else if(l<0) { l=0; }
  if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight) {
    t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
  } else if(t<0) { t=0; }
  this.oDiv.style.left=l+'px';
  this.oDiv.style.top=t+'px';
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>

LimitDrag 只覆寫了 fnMove 加入邊界判斷,其餘行為完全沿用 Drag,這正是原型繼承帶來的複用價值。以上就是本文全部內容,希望對你的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved