DIV CSS 佈局教程網

JavaScript 事件綁定及深入探討
編輯:JavaScript基礎知識     

事件綁定主要分為兩種:一種是傳統事件綁定(內聯模型/腳本模型),另一種是現代事件綁定(DOM2 級模型)。後者是在前者的基礎上,提供了更強大的功能。

一、傳統事件綁定的問題

// 腳本模型把一個函式賦值給某個事件處理函式
var box = document.getElementById('box');   // 獲取元素
box.onclick = function(){                     // 元素點擊觸發事件
  alert('Lee');
}

問題一:同一個事件處理函式被觸發兩次時會互相覆蓋。

window.onload = function(){ alert('Lee'); }      // 第一組程式
window.onload = function(){ alert('Mr.Lee'); }   // 第二組程式
// PS:當兩組程式同時存在時,後者會把前者完全覆蓋,導致前面的 onload 失效;
// 解決方案:
window.onload = function(){          // 第一組事件處理程式,會被覆蓋
  alert('Lee');
}
if(typeof window.onload == 'function'){
  var saved = null;                  // 建立一個保存器
  saved = window.onload;             // 把之前的 onload 保存起來
}
window.onload = function(){          // 下一個要執行的事件
  if(saved)saved();                  // 若有則先執行之前保存的事件
  alert('Mr.Lee');                   // 執行本事件的程式碼
}

問題二:事件切換器。

box.onclick = toBlue;   // 第一次執行 toBlue()
function toRed(){
  this.className = 'red';
  this.onclick = toBlue;   // 第三次執行 toBlue(),如此來回切換
}
function toBlue(){
  this.className = 'blue';
  this.onclick = toRed;    // 第二次執行 toRed()
}
// 這個切換器在擴充時會出現問題:
// 1. 若增加一個執行函式,會被覆蓋
box.onclick = toAlert;   // 被增加的函式
box.onclick = toBlue;    // toAlert 被覆蓋了
// 2. 若解決覆蓋問題,就必須包含同時執行,但可讀性降低
box.onclick = function(){
  toAlert();          // 第一次不會被覆蓋,但第二次又被覆蓋
  toBlue.call(this);  // 還必須把 this 傳遞到切換器裡
}

綜合以上三個問題——覆蓋、可讀性、this 傳遞——我們可以建立一個自訂的事件處理函式:

function addEvent(obj,type,fn){
  var saved = null;                       // 保存每次觸發的事件處理函式
  if(typeof obj['on'+type] == 'function'){ // 判斷是否存在事件
    saved = obj['on'+type];               // 如果有,保存起來
  }
  obj['on'+type] = function(){
    if(saved)saved();                     // 執行上一個
    fn.call(this);                        // 執行函式,把 this 傳遞進去
  }
}
addEvent(window,'load',function(){ alert('Lee'); });
addEvent(window,'load',function(){ alert('Mr.Lee'); });

二、W3C 事件處理函式

DOM2 級事件定義了兩個方法,用於添加與刪除事件的處理程序:addEventListener() 與 removeEventListener()。所有 DOM 節點都包含這兩個方法,它們都接受三個參數:事件名、函式,以及表示冒泡或捕獲的布林值(true 表示捕獲,false 表示冒泡)。

window.addEventListener('load',function(){ alert('Lee'); },false);
window.addEventListener('load',function(){ alert('Mr.Lee'); },false);
// PS:W3C 事件綁定的好處:1. 不需自訂;2. 可屏蔽相同的函式;3. 可設定冒泡與捕獲
window.addEventListener('load',init,false);   // 第一次執行
window.addEventListener('load',init,false);   // 第二次被屏蔽
function init(){ alert('Lee'); }

// 事件切換器
window.addEventListener('load',function(){
  var box = document.getElementById('box');
  box.addEventListener('click',function(){ alert('Lee'); },false);  // 不會被覆蓋或誤刪
  box.addEventListener('click',toBlue,false);                       // 引入切換
},false);
function toRed(){
  this.className = 'red';
  this.removeEventListener('click',toRed,false);   // 移除事件處理函式
  this.addEventListener('click',toBlue,false);   // 添加需要切換的事件處理函式
}
function toBlue(){
  this.className = 'blue';
  this.removeEventListener('click',toBlue,false);
  this.addEventListener('click',toRed,false);
}

// 設定冒泡與捕獲階段
document.addEventListener('click',function(){ alert('document'); },true);   // 捕獲
document.addEventListener('click',function(){ alert('Lee'); },false);       // 冒泡

三、IE 事件處理函式

IE 實作了與 DOM 類似的兩個方法:attachEvent() 與 detachEvent(),它們都接受相同的參數:事件名與函式。

// 使用這組函式時的區別:
// 1. IE 不支援捕獲,只支援冒泡;
// 2. IE 添加事件不能屏蔽重複的函式;
// 3. IE 中的 this 指向 window 而非 DOM 物件;
// 4. 傳統事件上 IE 無法接到 event 物件,但使用 attachEvent() 卻可以;
window.attachEvent('onload',function(){
  var box = document.getElementById('box');
  box.attachEvent('onclick',toBlue);
});
function toRed(){
  var that = window.event.srcElement;
  that.className = 'red';
  that.detachEvent('onclick',toRed);
  that.attachEvent('onclick',toBlue);
}
function toBlue(){
  var that = window.event.srcElement;
  that.className = 'blue';
  that.detachEvent('onclick',toBlue);
  that.attachEvent('onclick',toRed);
}
// 相容 IE 與 W3C 的事件切換器函式
function addEvent(obj,type,fn){
  if(obj.addEventListener){
    obj.addEventListener(type,fn);
  }else if(obj.attachEvent){
    obj.attachEvent('on'+type,fn);
  }
}
function removeEvent(obj,type,fn){
  if(obj.removeEventListener){
    obj.removeEventListener(type,fn);
  }else if(obj.detachEvent){
    obj.detachEvent('on'+type,fn);
  }
}
function getTarget(evt){
  if(evt.target){
    return evt.target;
  }else if(window.event.srcElement){
    return window.event.srcElement;
  }
}

四、事件物件補充

// 1. relatedTarget
// 這個屬性可在 mouseover 與 mouseout 事件中取得從哪裡移入、從哪裡移出的 DOM 物件
box.onmouseover = function(evt){ alert(evt.relatedTarget); }  // 移入 box 前的元素
box.onmouseout = function(evt){ alert(evt.relatedTarget); }   // 移出 box 後到的元素
// IE 提供了兩組對應屬性:fromElement 與 toElement
function getRelatedTarget(evt){
  var e = evt || window.event;
  if(e.srcElement){                 // 支援 srcElement 表示 IE
    if(e.type == 'mouseover'){ return e.fromElement; }
    else if(e.type == 'mouseout'){ return e.toElement; }
  }else if(e.relatedTarget){        // 支援 relatedTarget 表示 W3C
    return e.relatedTarget;
  }
}
// 2. 阻止事件的預設行為
// 超連結的預設行為是點擊後跳轉,阻止它就能屏蔽跳轉、實現自訂操作
link.onclick = function(){
  alert('Lee');
  return false;   // 直接回傳 false 就不會跳轉
}
// PS:回傳 false 雖可達成目的,但有漏洞:
// 第一,程式碼必須寫到最後,中間程式碼執行後可能到不了 return false;
// 第二,return false 寫到最前,後續自訂操作就會失效;
// 解決方案:在最前面就阻止預設行為,後面仍能執行程式碼
function preDef(evt){
  var e = evt || window.event;
  if(e.preventDefault){
    e.preventDefault();     // W3C
  }else{
    e.returnValue = false;  // IE
  }
}
// 3. 右鍵選單事件 contextmenu
// 右擊網頁時會出現系統預設選單,可用 contextmenu 事件改成自訂選單,前提是取消右擊預設行為
addEvent(window,'load',function(){
  var text = document.getElementById('text');
  addEvent(text,'contextmenu',function(evt){
    var e = evt || window.event;
    preDef(e);                              // 阻止預設行為
    var menu = document.getElementById('menu');
    menu.style.left = e.clientX + 'px';     // 自訂選單位置
    menu.style.top = e.clientY + 'px';
    menu.style.visibility = 'visible';      // 設為可見
    addEvent(document,'click',function(){
      document.getElementById('myMenu').style.visibility = 'hidden';  // 點擊後隱藏
    });
  });
});
// 4. 卸載前事件 beforeunload
// 這個事件可在離開本頁時給出提示,對應「離開」或「返回」操作
addEvent(window,'beforeunload',function(evt){
  var e = event || window.event;
  var message = '是否離開此頁?';
  e.returnValue = message;
  return message;
});
// 5. 滑鼠滾輪 mousewheel 與 DOMMouseScroll
// 用於取得滑鼠上下滾輪的距離
addEvent(document,'mousewheel',function(evt){ alert(getWD(evt)); });    // 非 Firefox
addEvent(document,'DOMMouseScroll',function(evt){ alert(getWD(evt)); }); // Firefox
function getWD(evt){
  var e = evt || window.event;
  if(e.wheelDelta){          // mousewheel 事件的滾動值保存在 wheelDelta
    return e.wheelDelta;
  }else if(e.detail){        // DOMMouseScroll 事件的滾動值保存在 detail
    return -e.detail*30;     // 保持計算一致
  }
}

從傳統綁定的痛點出發,一路走到 W3C 與 IE 的相容處理,事件綁定的核心其實就在於「如何安全地添加、移除與切換事件處理函式」,並妥善處理 this 與事件物件的跨瀏覽器差異。

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