全域禁用右鍵選單,但 <input>、<textarea> 等表單元素保持可用(複製、貼上、拼寫檢查)。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>選擇性禁用右鍵</title>
<style>
html,body{height:100%}
#thediv{width:150px;height:50px;background:#CCC;}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
// 判斷事件目標標籤是否在白名單
function isAllowedTag(e, allowedTags) {
e = $.event.fix(e); // 修正事件物件跨瀏覽器相容
var target = e.target || e.srcElement;
if (allowedTags && $.inArray(target.tagName.toUpperCase(), allowedTags) === -1) {
return false;
}
return true;
}
$(document).on('contextmenu', function(e) {
// 白名單:INPUT, TEXTAREA
if (!isAllowedTag(e, ['INPUT', 'TEXTAREA'])) {
e.preventDefault(); // 阻止預設右鍵選單
return false;
}
return true; // 白名單元素保留原生行為
});
});
</script>
</head>
<body>
<div id="thediv">此區域右鍵被禁用</div>
<textarea placeholder="這裡可以右鍵"></textarea>
</body>
</html>
$.event.fix(e):統一事件物件,修正 IE 缺少 target、preventDefault 等問題。e.target || e.srcElement:取得觸發事件的實際元素。$.inArray(tag, arr) === -1:判斷標籤是否不在白名單。e.preventDefault():阻止瀏覽器預設右鍵選單,必須搭配 return false 阻止事件冒泡,否則父層仍會彈出選單。// 依需求擴充
var WHITELIST = ['INPUT', 'TEXTAREA', 'SELECT', 'A']; // 連結也可右鍵
$(document).on('contextmenu', function(e) {
if (!isAllowedTag(e, WHITELIST)) {
e.preventDefault();
return false;
}
});
document.addEventListener('contextmenu', function(e) {
var allowed = ['INPUT', 'TEXTAREA', 'SELECT', 'A'];
if (!allowed.includes(e.target.tagName)) {
e.preventDefault();
}
}, false);
iframe,需在 iframe 內部也綁定相同邏輯。touchstart + preventDefault)。