萬盛學電腦網

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

網頁禁止滑鼠右鍵、文字選取:簡易代碼與現代替代方案

傳統簡易代碼 (僅阻擋基本操作)

<script>
document.oncontextmenu = function() { return false; }; // 禁用右鍵選單
document.onselectstart = function() { return false; }; // 禁用文字選取 (IE/舊版)
</script>

或寫成單行:

<script>document.oncontextmenu=document.onselectstart=function(){return false;}</script>

現代 CSS 方案 (推薦,無 JS 依賴)

<style>
.no-select {
    -webkit-user-select: none; /* Chrome/Safari */
    -moz-user-select: none;    /* Firefox */
    -ms-user-select: none;     /* IE10+ */
    user-select: none;         /* 標準 */
}
</style>

<body class="no-select">...</body>
<!-- 或針對特定元素 -->
<div class="no-select">不可選取的內容</div>

JS 進階:允許特定區域選取

document.addEventListener('contextmenu', function(e) {
    // 僅在非輸入框、非代碼區阻擋右鍵
    if (!e.target.closest('input, textarea, pre, code, [contenteditable]')) {
        e.preventDefault();
    }
}, false);

document.addEventListener('selectstart', function(e) {
    if (!e.target.closest('input, textarea, pre, code, [contenteditable]')) {
        e.preventDefault();
    }
}, false);

重要提醒

前端阻擋只能阻擋誠實的使用者,無法防止資料被複製。

  • 查看原始碼 (Ctrl+U)、開發者工具、列印存檔、停用 JS、爬蟲程式均可輕易取得內容。
  • 若內容涉及版權/機密,請從後端授權、加密、水印、法律手段著手。
  • 過度阻擋會嚴重損害使用者體驗 (無法複製代碼、查字典、翻譯等),請審慎評估必要性。

總結

簡易需求用 CSS user-select: none + oncontextmenu 即可;進階需求用事件委派精準控制;核心資料保護請勿依賴前端。

copyright © 萬盛學電腦網 all rights reserved