方案一:全域禁用 (最簡單)
document.body.oncontextmenu = function () { return false; };
方案二:保留輸入框/文字區域右鍵 (推薦)
document.oncontextmenu = function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
var tag = target.tagName.toLowerCase();
var type = target.type?.toLowerCase();
// input[type=text]、textarea、contenteditable 允許右鍵
if (tag === 'textarea' ||
(tag === 'input' && type === 'text') ||
target.isContentEditable) {
return true;
}
return false;
};
方案三:jQuery 版 (方便委派)
$(document).on('contextmenu', function (e) {
var $t = $(e.target);
if ($t.is('textarea, input[type=text], [contenteditable]')) return true;
return false;
});
注意事項
- 無法阻擋瀏覽器原生開發工具、擴充功能選單
- 僅提高門檻,無法完全防止圖片/文字被複製
- 現代網站建議改用
user-select: none CSS 限制選取
CSS 輔助防選取
.no-select { user-select: none; -webkit-user-select: none; -ms-user-select: none; }