DIV CSS 佈局教程網

自訂右鍵選單:攔截 contextmenu 的三個步驟
編輯:JavaScript綜合知識     

把滑鼠右鍵的預設選單換成自己的內容,在很多內部系統、圖片管理介面裡很實用。原理只有三步:攔下 contextmenu 事件、在滑鼠位置產生一個浮層、點其他地方就收起來。

原始寫法:用 IE 的 createPopup

<script type="text/javascript">
var oPopup = window.createPopup();     // IE 專屬:建立一個獨立的彈出視窗

function PopMenu(id) {
  var oPopBody = oPopup.document.body;
  oPopBody.style.backgroundColor = "buttonface";
  oPopBody.style.border = "solid black 1px";

  var TableBegin = "<table style='border:0; width:100%; font-size:12px;' cellpadding='0' cellspacing='0'>";

  var Tr1 = "<tr><td valign='middle' style='height:20px;'"
        + " onmousemove=\"this.bgColor='highlight'; this.style.color='highlighttext'\""
        + " onmouseout=\"this.bgColor=''; this.style.color=''\""
        + " onclick=\"parent.window.open('/news/view.asp?id=" + id + "');\">查看新聞</td></tr>";

  var TrBr1 = "<tr><td style='background-color:ThreeDShadow; height:1px;'></td></tr>";

  var Tr2 = "<tr><td valign='middle' style='height:20px; cursor:hand;'"
        + " onmousemove=\"this.bgColor='highlight'; this.style.color='highlighttext'\""
        + " onmouseout=\"this.bgColor=''; this.style.color=''\""
        + " onclick=\"parent.document.frames['main'].location='divdiv.aspx?id=" + id + "';\">"
        + "查看新聞</td></tr>";

  oPopBody.innerHTML = TableBegin + Tr1 + TrBr1 + Tr2 + "</table>";

  oPopup.show(event.x, event.y, 90, 41, document.body);   // 座標、寬、高、所屬文件
  return false;                                            // 阻止預設選單
}
</script>

掛在元素上時,用 oncontextmenu 並回傳 false:

<a href="javascript:void(0);" oncontextmenu="PopMenu(1); return false;">
  <img src="1.gif" style="border:0; width:150px; height:110px; cursor:hand" alt="" />
</a>

window.createPopup() 是 IE 獨有的 API,它建立的是一個類似獨立小視窗的物件,好處是不受頁面 overflow 裁切,壞處是只有 IE 能用,而且那個 ThreeDShadow 系統色彩關鍵字也只在 IE 家族有效。

跨瀏覽器的現代寫法

用一個普通的 div 當選單,靠 position: fixed 定位在滑鼠座標上即可:

<style>
#ctxMenu {
  position: fixed;
  display: none;
  z-index: 1000;
  min-width: 120px;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0,0,0,.15);
  font-size: 13px;
  padding: 4px 0;
}
#ctxMenu button {
  display: block; width: 100%; text-align: left;
  border: 0; background: none; padding: 6px 16px; cursor: pointer;
}
#ctxMenu button:hover, #ctxMenu button:focus { background: #1371A0; color: #fff; }
</style>

<div id="ctxMenu" role="menu">
  <button type="button" data-act="view">查看新聞</button>
  <button type="button" data-act="edit">編輯</button>
</div>

<script>
var menu = document.getElementById('ctxMenu');

document.addEventListener('contextmenu', function (e) {
  // 只在指定元素上攔截,其他區域保留瀏覽器預設選單
  if (!e.target.closest('.has-menu')) return;

  e.preventDefault();                       // 這就是「回傳 false」的標準寫法
  menu.style.display = 'block';

  // 先量尺寸再定位,避免選單超出視窗邊界
  var w = menu.offsetWidth, h = menu.offsetHeight;
  menu.style.left = Math.min(e.clientX, window.innerWidth  - w) + 'px';
  menu.style.top  = Math.min(e.clientY, window.innerHeight - h) + 'px';

  menu.querySelector('button').focus();
});

// 點選單以外的地方、滾動、按 Escape 都收起來
['click', 'scroll', 'keydown'].forEach(function (evt) {
  document.addEventListener(evt, function (e) {
    if (evt === 'keydown' && e.key !== 'Escape') return;
    if (evt === 'click' && menu.contains(e.target)) return;
    menu.style.display = 'none';
  });
});

menu.addEventListener('click', function (e) {
  var act = e.target.dataset.act;
  if (!act) return;
  // 依 act 執行對應動作
  menu.style.display = 'none';
});
</script>

幾個實務上的判斷

  • 不要全域攔截。瀏覽器右鍵選單承載了「檢查」「存圖」「複製連結」等使用者習慣,全域覆寫會招致反感。只在你真正提供了替代功能的元件上攔截,並且保留一個「用 Shift + 右鍵」顯示系統選單的後門。
  • 鍵盤也要能用。桌面應用裡 Shift + F10 或鍵盤的 Menu 鍵等同右鍵,記得一併處理,否則純鍵盤使用者會完全無法存取這些功能。
  • 長按等於右鍵。觸控裝置上長機會觸發 contextmenu,但 event 上沒有可靠的 clientX,需要用 touchend 時的位置來定位。
  • 選單要能被捲動。項目多時給 max-height 與 overflow: auto,並記得在滾動時重新計算座標。

原始的 createPopup 方案在今日已無實用價值,但它示範的「攔截 → 定位 → 提供選項」三步驟,與上面這份標準寫法完全一致。

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