萬盛學電腦網

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

document.execCommand() 完整指南:富文本編輯指令大全、兼容性與現代替代方案

document.execCommand() 是早期瀏覽器提供的富文本編輯命令 API,雖已被標準廢棄,但在舊版編輯器、CMS 維護中仍廣泛存在。本文整理全部命令、參數詳解、兼容性現狀、避坑指南與現代 ContentEditable / Input Events / Editing API 替代方案。

一、命令大全 (按功能分類)

1. 基礎編輯

命令參數作用狀態查詢
bold—切換粗體queryCommandState('bold')
italic—切換斜體queryCommandState('italic')
underline—切換下劃線queryCommandState('underline')
strikethrough—切換刪除線queryCommandState('strikethrough')
superscript—上標queryCommandState('superscript')
subscript—下標queryCommandState('subscript')
removeFormat—清除選區內聯格式—

2. 字體與顏色

命令參數 (value)作用
fontName字體名 (如 "Arial")設置字體
fontSize1-7 (傳統) / CSS 尺寸 (現代)設置字號
foreColor顏色值 (#RRGGBB / rgb() / 名稱)前景色
backColor / hiliteColor顏色值背景色 / 高亮色

3. 段落與塊級格式

命令參數作用
formatBlock標簽名 (<h1>、<p>、<blockquote>)設置塊級標簽
indent—增加縮進
outdent—減少縮進
justifyLeft—左對齊
justifyCenter—居中
justifyRight—右對齊
justifyFull—兩端對齊

4. 列表操作

命令參數作用
insertOrderedList—切換有序列表
insertUnorderedList—切換無序列表

5. 插入元素

命令參數作用
createLinkURL 字符串插入/修改鏈接 (彈出對話框若參數為 null)
unlink—移除鏈接
insertImage圖片 URL插入圖片
insertHorizontalRule—插入 <hr>
insertHTMLHTML 字符串插入任意 HTML (現代瀏覽器支持)
insertText文本插入純文本 (現代)

6. 剪貼板與撤銷/重做

命令參數作用
copy—複製選區到剪貼板
cut—剪切選區到剪貼板
paste—從剪貼板粘貼
undo—撤銷
redo—重做
delete—刪除選區
selectAll—全選

7. 其他


// 只讀/編輯模式切換
document.execCommand('defaultParagraphSeparator', false, 'p'); // 回車產生 

而非

// 開啟/關閉設計模式 document.designMode = 'on'; // 整頁可編輯 element.contentEditable = 'true'; // 單元素可編輯

二、核心 API 簽名


document.execCommand(commandId, showUI, value) → boolean
// commandId: 命令名 (大小寫不敏感)
// showUI: 是否顯示默認 UI 對話框 (如 createLink 彈出輸入框),現代瀏覽器多忽略
// value: 命令參數 (字體名、顏色、URL 等)
// 返回: 執行成功 true / 失敗 false

狀態查詢


document.queryCommandState('bold');     // true/false 當前選區是否粗體
document.queryCommandValue('fontName'); // 返回當前字體名
document.queryCommandEnabled('bold');   // 當前上下文是否可執行
document.queryCommandSupported('bold'); // 瀏覽器是否支持該命令
document.queryCommandIndeterm('bold');  // 選區部分粗體 (混合狀態)

三、兼容性現狀 (2024)

  • MDN 狀態:Deprecated (已棄用),不在任何標準軌道
  • 瀏覽器支持:Chrome/Edge/Firefox/Safari 仍保留實現,但可能隨時移除
  • 差異點:
    • fontSize:舊版接受 1-7,現代接受 CSS 值 ('14px')
    • insertHTML / insertText:僅現代瀏覽器支持
    • styleWithCSS:document.execCommand('styleWithCSS', true) 切換生成 <span style="..."> vs <b>,行為不一致

四、經典避坑指南

1. 必須在可編輯上下文中調用


// ❌ 普通頁面直接調用無效
document.execCommand('bold'); // false

// ✅ 正確:聚焦可編輯元素
const editor = document.getElementById('editor');
editor.contentEditable = 'true';
editor.focus();
document.execCommand('bold'); // true

2. 剪貼板命令需用戶手勢觸發


// ❌ 自動執行被攔截
document.execCommand('copy'); // false, 安全策略

// ✅ 在 click 事件中執行
btn.addEventListener('click', () => {
    editor.focus();
    document.execCommand('copy');
});

3. 選區丟失問題 (iframe/模態框)


// 解決:保存/恢復選區
let savedRange = null;
function saveSelection() {
    const sel = window.getSelection();
    if (sel.rangeCount) savedRange = sel.getRangeAt(0).cloneRange();
}
function restoreSelection() {
    if (savedRange) {
        const sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(savedRange);
    }
}
// 在彈窗關閉前 saveSelection,恢復焦點後 restoreSelection

4. 輸入法合成事件干擾

中文輸入法合成期間 execCommand 可能失效或產生亂碼,監聽 compositionstart/end 暫停/恢復處理。

五、現代替代方案 (標準化路徑)

1. Input Events Level 2 (推薦)


// 派發標準輸入事件,瀏覽器原生處理撤銷棧、輸入法、協同編輯
function execInputCommand(editor, command, value) {
    const event = new InputEvent('beforeinput', {
        inputType: command, // 'insertText', 'deleteContent', 'formatBold' 等
        data: value,        // 參數值
        bubbles: true,
        cancelable: true,
        composed: true
    });
    return editor.dispatchEvent(event); // 返回是否被取消
}

// 使用
editor.dispatchEvent(new InputEvent('beforeinput', {
    inputType: 'insertText',
    data: 'Hello '
}));
editor.dispatchEvent(new InputEvent('beforeinput', {
    inputType: 'formatBold'
}));

支持的 inputType:insertText、insertLineBreak、deleteContent、deleteByCut、formatBold、formatItalic、formatUnderline、formatStrikethrough、formatSuperscript、formatSubscript、formatJustifyLeft/Center/Right/Full、formatIndent/Outdent、insertOrderedList/UnorderedList、insertLink (需 data 為 URL)、removeFormat 等。

2. Selection + Range + DOM API (底層控制)


// 獲取選區
const sel = window.getSelection();
if (sel.rangeCount) {
    const range = sel.getRangeAt(0);
    // 刪除選區內容
    range.deleteContents();
    // 插入節點
    range.insertNode(document.createTextNode('新文本'));
    // 折疊光標到末尾
    range.collapse(false);
    sel.removeAllRanges();
    sel.addRange(range);
}

3. 成熟富文本編輯器框架 (生產首選)

  • TipTap (ProseMirror 封裝,Vue/React、TypeScript、擴展豐富)
  • Slate.js (React、高度可定製、數據模型優雅)
  • Lexical (Meta 開源、性能極佳、協同編輯就緒)
  • Quill (成熟、模組化、Delta 格式)
  • CKEditor 5 (企業級、GPU 加速、實時協作)
  • ProseMirror (核心引擎、極致可定製)

六、遷移策略:從 execCommand 到現代架構

  1. 識別依賴:全局搜索 execCommand、queryCommandState、queryCommandValue
  2. 分層替換:
    • 簡單格式 (粗體/斜體/鏈接) → InputEvent 派發
    • 複雜結構 (表格/嵌入/協同) → 引入 TipTap/Slate/Lexical
  3. 數據模型遷移:HTML 字符串 → 結構化 JSON (ProseMirror Doc / Slate Value / Lexical Node)
  4. 漸進增強:新功能用現代架構,舊模塊逐步重寫

七、總結

document.execCommand() 是瀏覽器早期為富文本編輯提供的「瑞士軍刀」,雖然功能全但行為不一致、標準已廢棄。新項目嚴禁使用,直接選型現代編輯器框架;舊項目維護時,封裝統一 EditorCommand 適配層隔離差異,並制定遷移計劃。核心原則:**編輯行為交給瀏覽器原生 Input Events 或成熟引擎,業務層只操作結構化數據模型**。

copyright © 萬盛學電腦網 all rights reserved