萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 禁用文字選取與複製:user-select 全屬性值與無障礙策略

標準屬性與跨瀏覽器寫法

.no-select {
  -webkit-user-select: none; /* Safari / Chrome ≤52 / iOS */
  -moz-user-select: none;    /* Firefox */
  -ms-user-select: none;     /* IE10+ / Edge Legacy */
  user-select: none;         /* 標準:Chrome 53+, Firefox 69+, Safari 13+, Edge 79+ */
}

user-select 五大取值行為對比

值行為描述典型場景
none元素及子元素文字**不可發起選取**。若從外部拖選進入,**仍可選中**內部文字。UI 控件、圖標字體、拖拽手柄、遊戲區
auto (預設)可編輯元素 (input/textarea/contenteditable) 可選;其餘不可選。重置繼承的 none
text文字可選,**不限制選取範圍**,可跨元素邊界選取。文章區、代碼區、文檔內容
element**僅元素內部發起選取有效**,選取範圍**被限制在元素邊界內**,不可跨出。獨立可選卡片、代碼塊、引用區
all單擊/觸摸即**選取整個元素內容** (Firefox 53+, Chrome 53+)。一次性複製區:Token、代碼片段、色值

區域性控制策略

/* 1. 全站禁選,僅內容區放開 */
body { user-select: none; }
.article-content, .code-block { user-select: text; }
.code-block { user-select: all; } /* 單擊全選代碼 */

/* 2. 拖拽時暫時全局禁選 */
body.dragging * { user-select: none; }

/* 3. 保留語義複製:視覺不可選但 Ctrl+C 有效 */
.copyable {
  user-select: none;
  position: relative;
}
.copyable::before {
  content: attr(data-text);
  position: absolute; inset: 0;
  color: transparent;
  user-select: text; /* 偽元素文字可選 */
  pointer-events: none;
}

IE9 及以下兼容方案

<div class="no-select" onselectstart="return false;">...</div>

.no-select {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* IE6-9 專用表達式 (不推薦生產) */
* html .no-select { /* IE6 */
  /* behavior: url(noselect.htc); */
}
*:first-child+html .no-select { /* IE7 */ }

**現代建議**:放棄 IE9- 支援,或引入 legacy-user-select Polyfill。

輸入框保護:防止誤禁選

/* 全局禁選後,必須顯式恢復表單元素 */
input, textarea, select, [contenteditable] {
  -webkit-user-select: text !important;
  -moz-user-select: text !important;
  -ms-user-select: text !important;
  user-select: text !important;
}

無障礙與用戶體驗原則

  1. 最小範圍原則:僅針對**非文字語義元素** (圖標、滑塊、Canvas、拖拽手柄) 禁選。
  2. 禁止全站禁選:嚴重損害螢幕閱讀器、翻譯工具、密碼管理器、複製連結、引用分享等核心功能。
  3. 提供替代複製途徑:代碼區加「複製按鈕」 (navigator.clipboard.writeText()) 優於依賴原生選取。
  4. 尊重減動偏好:@media (prefers-reduced-motion: reduce) { .no-select { user-select: auto; } }。
  5. 高對比模式:確保禁選不影響系統色渲染。

常見誤區

user-select: none 能防止複製
**否**。用戶仍可:開發者工具複製、列印頁面、檢視源碼、截圖 OCR、禁用 CSS、JS 注入。僅提高門檻,非安全手段。
-webkit-user-select 只需寫一個
**需四前綴並存**以覆蓋舊版本。現代構建工具 (Autoprefixer) 自動處理,源碼僅寫標準屬性。
pointer-events: none 等同禁選
**不同**。pointer-events: none 連點擊/懸停事件都穿透,元素完全不可互動;user-select: none 僅禁文字選取,點擊/聚焦仍生效。
copyright © 萬盛學電腦網 all rights reserved