// 開啟/關閉設計模式
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 到現代架構
- 識別依賴:全局搜索
execCommand、queryCommandState、queryCommandValue
- 分層替換:
- 簡單格式 (粗體/斜體/鏈接) →
InputEvent 派發
- 複雜結構 (表格/嵌入/協同) → 引入 TipTap/Slate/Lexical
- 數據模型遷移:HTML 字符串 → 結構化 JSON (ProseMirror Doc / Slate Value / Lexical Node)
- 漸進增強:新功能用現代架構,舊模塊逐步重寫
七、總結
document.execCommand() 是瀏覽器早期為富文本編輯提供的「瑞士軍刀」,雖然功能全但行為不一致、標準已廢棄。新項目嚴禁使用,直接選型現代編輯器框架;舊項目維護時,封裝統一 EditorCommand 適配層隔離差異,並制定遷移計劃。核心原則:**編輯行為交給瀏覽器原生 Input Events 或成熟引擎,業務層只操作結構化數據模型**。