萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現自定義右鍵選單完整教學

原生 JS 打造專屬右鍵上下文選單

瀏覽器默認右鍵選單功能有限,通過攔截 contextmenu 事件並結合座標定位,我們能構建功能豐富的自定義右鍵選單,廣泛應用於編輯器、文件管理器、數據表格等複雜交互場景。

核心實現原理

  1. 監聽 document.body.oncontextmenu 事件
  2. 調用 event.preventDefault() 阻止默認選單
  3. 獲取滑鼠座標 event.pageX、event.pageY
  4. 將自定義選單 position: absolute 定位到該座標並顯示
  5. 點擊頁面其他區域(onclick)隱藏選單

完整功能代碼

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>自定義右鍵選單演示</title>
  <style>
    html, body { height: 100%; margin: 0; }
    #mydiv { width: 300px; height: 300px; background: #ff7400; }
    #ctxMenu {
      background: #ff7400; list-style: none; position: absolute;
      padding: 0; border: 1px solid #000; visibility: hidden; z-index: 999;
    }
    #ctxMenu li { padding: 8px 16px; cursor: pointer; }
    #ctxMenu li:hover { background: #e66000; }
  </style>
</head>
<body>
  <div id="mydiv">右鍵點擊此區域試試</div>
  <h2 id="show"></h2>
  <input type="text" id="txt"><span id="help"></span>
  
  <ul id="ctxMenu">
    <li data-action="upload">上傳</li>
    <li data-action="download">下載</li>
    <li data-action="create">新建</li>
    <li data-action="cancel">取消</li>
  </ul>

  <script>
    const $ = id => document.getElementById(id);
    const ctx = $("ctxMenu");
    const help = $("help");

    // 阻止默認右鍵,顯示自定義選單
    document.body.oncontextmenu = e => {
      e.preventDefault();
      ctx.style.left = e.pageX + "px";
      ctx.style.top = e.pageY + "px";
      ctx.style.visibility = "visible";
    };

    // 點擊頁面任意處隱藏選單
    document.body.onclick = () => ctx.style.visibility = "hidden";

    // 選單項點擊處理(事件代理)
    ctx.onclick = e => {
      const action = e.target.dataset.action;
      if (action) {
        alert(`執行操作:${action}`);
        ctx.style.visibility = "hidden";
      }
    };

    // 輸入框輔助提示
    $("txt").onfocus = () => help.textContent = "請輸入金額";
    $("txt").onkeydown = e => {
      help.textContent = "";
      const code = e.keyCode;
      const allowed = (code >= 48 && code <= 57) || (code >= 96 && code <= 105) || 
                     [8, 13, 37, 39, 46, 110, 190].includes(code);
      if (!allowed) e.preventDefault();
    };
  </script>
</body>
</html>

生產級優化建議

  • 邊界檢測:防止選單超出視口,需根據 window.innerWidth/Height 調整位置
  • 多層級子選單:使用巢狀 <ul> + CSS :hover 實現
  • 鍵盤無障礙:支持 Esc 關閉、方向鍵導航、Enter 確認
  • 事件代理:在父級 <ul> 綁定點擊,避免為每個 <li> 綁定事件

這套方案零依賴、體積極小,適合對性能敏感或不想引入重型庫的項目。

copyright © 萬盛學電腦網 all rights reserved