滑鼠按鍵的值在不同瀏覽器有兩套完全不同的編碼,這是許多人寫拖曳或右鍵選單時踩過的坑。標準(W3C)與舊 IE 的定義如下:
右鍵剛好都是 2,左鍵與中鍵則完全不同,必須做轉換。
document.onmousedown = function (e) {
alert(getButton(e));
// e.button 為 W3C 標準;IE 則需從 window.event 取
};
function getButton(e) {
/*
* 1. window.event 在 IE 與 Chrome 都支援
* 2. 但 Chrome 同時也支援 W3C 標準
* 3. 因此當兩者都存在時,一律以 W3C 為準
*/
if (e) {
// 有 e 代表走標準路徑(含 Chrome)
return e.button;
} else if (window.event) {
switch (window.event.button) {
case 1: return 0; // 左鍵
case 4: return 1; // 中鍵
case 2: return 2; // 右鍵
case 0: return 2; // 部分 360 瀏覽器在未按下時回傳 0
}
}
}
關鍵在「先檢查 e 是否存在」。Chrome 同時支援 window.event 與標準的事件參數,如果先判斷 window.event,Chrome 就會走進 IE 分支而被錯誤轉換。反過來說,只要函式收到了 e 參數,就代表環境走的是標準模型,直接用 e.button 即可。這正是註解中「以 W3C 作為標準化依據」的意思。
今天的瀏覽器已全面支援標準事件模型,上面那套判斷不再需要:
document.addEventListener('mousedown', function (e) {
// e.button: 0 左鍵、1 中鍵、2 右鍵
console.log(e.button);
// e.buttons 是位元遮罩,可判斷多鍵同時按下
// bit 0 = 左鍵(1)、bit 1 = 右鍵(2)、bit 2 = 中鍵(4)
if (e.buttons & 1) console.log('左鍵按住中');
});
順帶一提,button 與 buttons 是兩個不同屬性:button 表示「這次事件是哪個鍵造成的」,buttons 表示「目前有哪些鍵被按住」,後者是位元運算,在實作拖曳時判斷「是否按住左鍵」比 button 更可靠,因為拖曳過程中若滑鼠移出視窗,button 的行為可能不如預期。
另外,若要處理的是右鍵選單,記得搭配 contextmenu 事件並呼叫 e.preventDefault() 來抑制預設選單,這比在 mousedown 中判斷 button === 2 更準確。