瀏覽器默認右鍵選單功能有限,通過攔截 contextmenu 事件並結合座標定位,我們能構建功能豐富的自定義右鍵選單,廣泛應用於編輯器、文件管理器、數據表格等複雜交互場景。
document.body.oncontextmenu 事件event.preventDefault() 阻止默認選單event.pageX、event.pageYposition: absolute 定位到該座標並顯示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> 綁定事件這套方案零依賴、體積極小,適合對性能敏感或不想引入重型庫的項目。