DIV CSS 佈局教程網

如何僅在指定元素上封鎖滑鼠右鍵選單
編輯:關於JavaScript     

最近在開發一個小功能時,需要在某個元素上「右擊」彈出自訂選單,透過這個選單來編輯右擊的項目。這就要求屏蔽掉瀏覽器預設的右鍵選單。

IE 與 FF 下的元素都有 oncontextmenu 這個方法,在 FF 中只要呼叫 event.preventDefault() 就能輕鬆達到效果;而 IE 並不支援這個方法,在 IE 中通常是透過在方法後 return false 來阻止預設事件。

一般我們阻止右鍵事件都是在全域攔截,也就是在 document 層面就把右鍵擋下來。但我現在想達成的效果是:只在特定區域阻止預設右鍵事件,其他區域則不受影響。

實驗中我發現,在 IE 下於綁定的方法裡 return false,可以在 document 層面阻止右鍵的預設行為;但一旦針對某個具體元素(例如 div),就失效了。

最後翻閱手冊才找到答案: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){
  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+ 與 FF,但 Opera 壓根就沒有 oncontextmenu 這個方法,因此無法簡單地透過它來實現,若想支援 Opera 還需要借助其他手段。

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