在特定元素上啟用自訂右鍵選單 (Context Menu),需監聽 contextmenu 事件並呼叫 preventDefault() 阻止瀏覽器預設選單。本文提供從簡易綁定到完整自訂選單元件的實作。
// 整頁禁用
document.addEventListener('contextmenu', e => e.preventDefault());
// 單一元素禁用
document.getElementById('myDiv').addEventListener('contextmenu', e => e.preventDefault());
// jQuery 寫法
$('#myDiv').on('contextmenu', e => e.preventDefault());
<style>
.custom-context-menu {
position: fixed; display: none; z-index: 9999;
min-width: 160px; padding: 4px 0; background: #fff; border: 1px solid #ddd;
border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,.15);
}
.custom-context-menu ul { margin: 0; padding: 0; list-style: none; }
.custom-context-menu li { padding: 6px 16px; cursor: pointer; white-space: nowrap; }
.custom-context-menu li:hover { background: #f0f0f0; }
.custom-context-menu li.divider { border-top: 1px solid #eee; padding: 0; height: 1px; }
</style>
<div id="targetArea" style="width:300px;height:200px;border:1px dashed #999;padding:20px;">
右鍵點擊此區域
</div>
<div id="ctxMenu" class="custom-context-menu">
<ul>
<li data-action="copy">複製</li>
<li data-action="paste">貼上</li>
<li class="divider"></li>
<li data-action="delete">刪除</li>
&ul>
</div>
<script>
const $target = $('#targetArea');
const $menu = $('#ctxMenu');
$target.on('contextmenu', e => {
e.preventDefault();
$menu.css({ left: e.clientX, top: e.clientY }).show();
});
$menu.on('click', 'li[data-action]', function() {
const action = $(this).data('action');
console.log('執行:', action);
$menu.hide();
// 實際業務邏輯...
});
// 點擊其他處關閉選單
$(document).on('click', () => $menu.hide());
// 捲動/縮放時關閉
$(window).on('scroll resize', () => $menu.hide());
// ESC 關閉
$(document).on('keydown', e => { if (e.key === 'Escape') $menu.hide(); });
</script>
const target = document.getElementById('targetArea');
const menu = document.getElementById('ctxMenu');
target.addEventListener('contextmenu', e => {
e.preventDefault();
menu.style.left = e.clientX + 'px';
menu.style.top = e.clientY + 'px';
menu.style.display = 'block';
});
menu.addEventListener('click', e => {
const item = e.target.closest('li[data-action]');
if (item) {
console.log('動作:', item.dataset.action);
menu.style.display = 'none';
}
});
['click', 'scroll', 'resize'].forEach(evt => window.addEventListener(evt, () => menu.style.display = 'none'));
document.addEventListener('keydown', e => { if (e.key === 'Escape') menu.style.display = 'none'; });
contextmenu 事件在 **長按觸發** (行動裝置) 亦會觸發,可搭配 touchstart/touchend 判斷長按。function showMenu(x, y) {
const menu = document.getElementById('ctxMenu');
menu.style.left = '0'; menu.style.top = '0'; menu.style.display = 'block'; // 先顯示以獲取尺寸
const mw = menu.offsetWidth, mh = menu.offsetHeight;
const vw = window.innerWidth, vh = window.innerHeight;
let left = Math.min(x, vw - mw - 10);
let top = Math.min(y, vh - mh - 10);
left = Math.max(10, left); top = Math.max(10, top);
menu.style.left = left + 'px';
menu.style.top = top + 'px';
}