萬盛學電腦網

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

讓 div 變身可編輯輸入框:contenteditable 實戰與瀏覽器默認樣式清除

場景:為什麼不用 <input>/<textarea>?

  • 需要富文本編輯(加粗、插圖、@提及、代碼塊)
  • 需要內聯編輯(點擊文字直接修改,無彈窗)
  • 需要完全自定義樣式,避免瀏覽器原生表單控件的跨平台差異(如 iOS Safari 的圓角、陰影、字體放大)

核心屬性:contenteditable

<div class="editor" contenteditable="true" data-placeholder="請輸入內容..."></div>

contenteditable="true" | "false" | "plaintext-only"(後者僅允許純文本,Chrome 87+ 支持)。

瀏覽器「智能」干擾與對策

啟用 contenteditable 後,瀏覽器會注入默認行為:

干擾現象原因解決方案
聚焦時出現藍色外框/邊框UA 樣式 outline / border.editor { outline: none; border: none; }
自動換行產生 <div>/<br>/<p>瀏覽器內部編輯器行為不一contenteditable="plaintext-only" 或 JS 規範化 document.execCommand('defaultParagraphSeparator', false, 'div')
粘貼帶入格式(顏色、字體、類名)剪貼板 HTML 內容直接插入監聽 paste 事件,e.preventDefault() + insertText(e.clipboardData.getData('text/plain'))
移動端虛擬鍵盤不彈出/異常瀏覽器未識別為輸入控件添加 inputmode="text"、role="textbox"、aria-multiline="true"
撤銷/重做 (Ctrl+Z) 失效瀏覽器歷史棧管理複雜內容困難自建撤銷棧(如 slate.js、prosemirror、lexical 框架)

最小可用實現(純 CSS + 少量 JS)

.editor {
  /* 基礎樣式 */
  min-height: 100px;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font: inherit;
  line-height: 1.6;
  color: #333;
  background: #fff;
  transition: border-color 0.2s, box-shadow 0.2s;
  /* 關鍵:清除瀏覽器默認 */
  outline: none;
  /* 佔位符模擬 */
}
.editor:empty:before {
  content: attr(data-placeholder);
  color: #999;
  pointer-events: none;
}
.editor:focus {
  border-color: #0066ff;
  box-shadow: 0 0 0 3px rgba(0, 102, 255, 0.15);
}
/* 禁止選中藍色高亮(可選) */
.editor ::selection { background: rgba(0, 102, 255, 0.2); }
// JS:純文本粘貼 + 回車換行控制
const editor = document.querySelector('.editor');
editor.addEventListener('paste', e => {
  e.preventDefault();
  const text = e.clipboardData.getData('text/plain');
  document.execCommand('insertText', false, text);
});
editor.addEventListener('keydown', e => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    document.execCommand('insertLineBreak'); // 或 insertParagraph
  }
});

生產級建議:拥抱成熟框架

手寫編輯器是「造輪子」的深坑(選區 Range/Selection API 極其繁瑣、跨瀏覽器差異巨大、協同編輯更是地獄)。推薦:

  • Slate.js:React 生態、可擴展、支援協同(需自建後端)
  • ProseMirror:架構最嚴謹、支援協同(y-prosemirror)、學習曲線陡峭
  • Lexical:Meta 開源、極致性能、原生支援協同、React/Vue/Vanilla 皆可
  • Tiptap:ProseMirror 封裝、Vue/React 雙支援、擴展生態豐富
  • Quill:輕量、易上手、但擴展性較弱

無障礙 (a11y) 必做清單

  1. role="textbox" + aria-multiline="true" + aria-label/aria-labelledby
  2. tabindex="0" 納入 Tab 順序
  3. 聚焦樣式明顯(:focus-visible)
  4. 錯誤狀態 aria-invalid="true" + aria-describedby="error-id"
  5. 動態內容更新區域 aria-live="polite"
「contenteditable 是把雙刃劍:輕量場景下的神器,複雜場景下的坑。認清業務複雜度,果斷選擇『自建』或『框架』。」
copyright © 萬盛學電腦網 all rights reserved