DIV CSS 佈局教程網

在特定元素上攔截滑鼠右鍵事件的實作與相容處理
編輯:關於JavaScript     

最近做一個小功能時,需要在某個元素上「右擊」觸發自訂選單,透過這個選單對右擊的項目進行編輯。前提当然是:把預設的右鍵選單擋掉。

IE 與 Firefox 的差異

IE 和 Firefox 下的元素都有 oncontextmenu 這個方法。在 Firefox 下,只要呼叫 event.preventDefault() 就能輕鬆達成效果;IE 不支援這個方法,一般得靠「在事件處理後 return false」來阻止預設行為。

通常我們攔右鍵是在全域攔截,也就是在 document 層面就把它擋下來。但這次的需求不同:只在特定區域阻止預設右鍵選單,其他區域不受影響。

踩到的坑

實驗下來發現,在 IE 中若把 return false 綁在 document 上,確實能阻止右鍵預設行為;但同樣的寫法用在具體元素(例如某個 div)上卻失效了。

解法:event.returnValue

翻手冊才找到答案:IE 的 event 物件有一個 returnValue 屬性,把它設為 false 就不會觸發預設的右鍵選單。

event.returnValue = false;

加上這一句,想要的效果就出來了。完整的 Demo:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>在某個元素上阻止滑鼠右鍵預設事件 DEMO</title>
<style>
body{font-size:12px; line-height:24px;
     font-family:Arial, Helvetica, sans-serif;}
#activeArea{width:300px; height:200px; background:#06C; color:#fff;}
#cstCM{ width:120px; background:#eee; border:1px solid #ccc;
        position:absolute; }
#cstCM ul{margin:0; padding:0;}
#cstCM ul li{ list-style:none; padding:0 10px; cursor:default;}
#cstCM ul li:hover{ background:#009; color:#fff;}
.splitTop{ border-bottom:1px solid #ccc;}
.splitBottom{border-top:1px solid #fff;}
</style>
<script>
function customContextMenu(event) {
    // 標準瀏覽器用 preventDefault,IE 用 returnValue
    event.preventDefault ? event.preventDefault() : (event.returnValue = false);

    var cstCM = document.getElementById('cstCM');
    cstCM.style.left = event.clientX + 'px';
    cstCM.style.top  = event.clientY + 'px';
    cstCM.style.display = 'block';

    document.onmousedown = clearCustomCM;
}

function clearCustomCM() {
    document.getElementById('cstCM').style.display = 'none';
    document.onmousedown = null;
}
</script>
</head>
<body>
<div id="cstCM" style="display:none;">
  <ul>
    <li>View</li>
    <li>Sort By</li>
    <li class="splitTop">Refresh</li>
    <li class="splitBottom">Paste</li>
    <li class="splitTop">Paste Shortcut</li>
    <li class="splitBottom">Property</li>
  </ul>
</div>
<div id="activeArea" oncontextmenu="customContextMenu(event)">
  Custom Context Menu Area
</div>
</body>
</html>

相容性與現代寫法

這個效果在 IE6+ 與 Firefox 上都能運作,但 Opera 完全沒有 oncontextmenu 這個方法,得靠其他手段繞路。

今天再寫同樣的功能,可以簡化很多:直接用 addEventListener('contextmenu', ...) 綁定事件,在處理器裡呼叫 event.preventDefault() 即可,不必再分叉判斷 IE。

area.addEventListener('contextmenu', function(event) {
    event.preventDefault();
    // 在 event.clientX / event.clientY 的位置顯示自訂選單
});

另外有兩點值得留意。一是可及性:自訂選單必須能用鍵盤操作,並提供適當的 ARIA 屬性,否則只靠右鍵的設計對只用鍵盤的使用者毫無意義。二是別全域封鎖右鍵——瀏覽器右鍵選單本身也是使用者的重要工具,只在明確需要自訂操作的元件上攔截,才是合理的做法。

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