萬盛學電腦網

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

JavaScript 自定義右鍵選單:createPopup 實現 (IE 專屬) 與現代跨瀏覽器替代方案

前言

早期 IE 專屬 window.createPopup() 可建立無邊框彈出層,常用於自定義右鍵選單。現代瀏覽器已移除此 API,需改用 contextmenu 事件 + 絕對定位 div 模擬。本文展示舊代碼邏輯與現代重構方案。

舊版 IE 專屬代碼 (僅供參考)

<script>
var oPopup = window.createPopup();
function PopMenu(id) {
    var oBody = oPopup.document.body;
    oBody.style.backgroundColor = 'buttonface';
    oBody.style.border = 'solid black 1px';
    var html = '<table style="border:0;width:100%;font-size:12px" cellpadding="0" cellspacing="0">'
        + '<tr><td valign="middle" style="height:20px" onmouseover="this.bgColor=\'highlight\';this.style.color=\'highlighttext\'" onmouseout="this.bgColor=\'\';this.style.color=\'\'" onclick="parent.window.open(\'/news/view.asp?id=' + id + '\')">查看新聞</td></tr>'
        + '<tr><td style="background:ThreeDShadow;height:1px"></td></tr>'
        + '<tr><td valign="middle" style="height:20px;cursor:hand" onmouseover="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>'
        + '</table>';
    oBody.innerHTML = html;
    oPopup.show(event.x, event.y, 90, 41, document.body);
    return false; // 取消預設右鍵選單
}
</script>

<body oncontextmenu="return false;"> <!-- 全頁禁用右鍵,改由元素綁定 -->
<a href="javascript:void(0);" oncontextmenu="return PopMenu(1);">
    <img src="1.gif" style="border:0;width:150px;height:110px;cursor:pointer" />
</a>
<iframe name="main" frameborder="0" width="100%" height="100%"></iframe>

現代跨瀏覽器實作 (推薦)

<style>
.custom-contextmenu {
    position: fixed; z-index: 9999;
    background: #fff; border: 1px solid #ccc; border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0,0,0,.15); min-width: 160px; padding: 4px 0;
    display: none;
}
.custom-contextmenu ul { list-style: none; margin: 0; padding: 0; }
.custom-contextmenu li { padding: 8px 16px; cursor: pointer; white-space: nowrap; }
.custom-contextmenu li:hover { background: #f0f0f0; }
.custom-contextmenu hr { margin: 4px 0; border: none; border-top: 1px solid #eee; }
</style>

<div id="ctxMenu" class="custom-contextmenu">
  <ul>
    <li data-action="view">查看新聞</li>
    <li data-action="frame">在框架開啟</li>
    <hr>
    <li data-action="copy">複製鏈接</li>
  </ul>
</div>

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

// 1. 右鍵事件:顯示選單並記錄目標
document.addEventListener('contextmenu', function (e) {
    // 可限定在特定區域/元素生效
    if (!e.target.closest('.has-contextmenu')) return;
    e.preventDefault();
    targetId = e.target.dataset.id || '1'; // 假設目標元素有 data-id
    ctxMenu.style.left = e.clientX + 'px';
    ctxMenu.style.top = e.clientY + 'px';
    ctxMenu.style.display = 'block';
});

// 2. 點擊選單項目執行動作
ctxMenu.addEventListener('click', function (e) {
    var li = e.target.closest('li');
    if (!li) return;
    var action = li.dataset.action;
    switch (action) {
        case 'view': window.open('/news/view.asp?id=' + targetId); break;
        case 'frame': parent.frames['main'].location = 'divdiv.aspx?id=' + targetId; break;
        case 'copy': navigator.clipboard.writeText(location.origin + '/news/view.asp?id=' + targetId); break;
    }
    hideMenu();
});

// 3. 點擊其他處關閉
document.addEventListener('click', hideMenu);
document.addEventListener('scroll', hideMenu, true);
window.addEventListener('resize', hideMenu);

function hideMenu() {
    ctxMenu.style.display = 'none';
    targetId = null;
}
</script>

關鍵差異對比

特性createPopup (IE舊版)現代 div 模擬
瀏覽器支援IE 5.5~11 (Edge 已移除)所有現代瀏覽器 (含移動端)
層級系統級彈出窗口,永遠置頂受 z-index 限制,需設定足夠高
樣式控制受限 (需在 popup.document 內寫樣式)完全 CSS 控制,支援動畫、響應式
事件模型IE 專屬事件屬性標準 DOM 事件
iframe 穿透可覆蓋 iframe需設定 iframe pointer-events:none 或將選單置於 iframe 外層

總結

createPopup 是 IE 歷史產物,現代開發請使用 contextmenu + 絕對定位 div 方案。本文提供完整可用的現代實作,支援鍵盤無障礙 (可擴展 Esc 關閉、Tab 導航)、響應式定位 (防止超出視口)、多實例管理。

copyright © 萬盛學電腦網 all rights reserved