在 contenteditable 編輯器中,使用者點擊工具列按鈕(如「插入圖片」)時,編輯器會失去焦點,導致 Selection/Range 物件丟失。IE6-8 更嚴重:甚至無法透過 document.selection.createRange() 正確還原插入點。WangEditor 以極簡代碼優雅解決了這個歷史難題。
var currentRange, _parentElem;
var supportRange = typeof document.createRange === 'function';
// 獲取當前 Range,並驗證是否在編輯器內部
function getCurrentRange() {
var selection, range, txt = $('editor');
if (supportRange) {
selection = document.getSelection();
if (selection.getRangeAt && selection.rangeCount) {
range = selection.getRangeAt(0);
_parentElem = range.commonAncestorContainer;
}
} else {
range = document.selection.createRange();
_parentElem = range.parentElement();
}
// 關鍵:確認 Range 容器在編輯器內部
if (_parentElem && (avalon.contains(txt, _parentElem) || txt === _parentElem)) {
parentElem = _parentElem;
return range;
}
return range;
}
// 保存選區(綁定在編輯器的 mouseup/keyup)
function saveSelection() {
currentRange = getCurrentRange();
}
// 還原選區(插入圖片前呼叫)
function restoreSelection() {
if (!currentRange) return;
var selection, range;
if (supportRange) {
selection = document.getSelection();
selection.removeAllRanges();
selection.addRange(currentRange);
} else {
range = document.selection.createRange();
range.setEndPoint('EndToEnd', currentRange);
if (currentRange.text.length === 0) {
range.collapse(false);
} else {
range.setEndPoint('StartToStart', currentRange);
}
range.select();
}
}
function insertImage(html) {
restoreSelection(); // 1. 先還原光標位置
if (document.selection) { // IE6-8
currentRange.pasteHTML(html); // 直接貼 HTML 片段(含 <img> 標籤)
} else { // 現代瀏覽器
document.execCommand("insertImage", false, html); // 傳圖片 URL
}
saveSelection(); // 2. 插入後再次保存(光標已移動)
}
avalon.bind($('post_input'), 'mouseup', function(e) { saveSelection(); });
avalon.bind($('post_input'), 'keyup', function(e) { saveSelection(); });
每當使用者在編輯器內點擊或輸入,即刻更新 currentRange,確保「最後一次有效選區」隨時可用。
pasteHTML vs execCommand| 特性 | pasteHTML (IE6-8) | execCommand('insertImage') (現代) |
|---|---|---|
| 參數 | 完整 HTML 字串(含 <img src="...">) | 圖片 URL 字串 |
| 多圖插入 | 一次可插入多張 | IE6-8 下僅插入第一張 |
| 標準化 | IE 私有 | 標準但行為不一 |
WangEditor 源碼統一用 execCommand,導致 IE 多圖失效。解決方案:IE 下改用 pasteHTML 插入完整 <img> 標籤。



現代專案建議改用 document.execCommand('insertHTML', false, html)(支援度良好)或直接操作 Range.insertNode(),完全避開歷史包袱。但理解 WangEditor 的這套機制,對維護舊專案、設計相容性方案極有參考價值。
WangEditor 用約 50 行代碼解決了困擾多年的「失焦插入」問題,核心在於:
mouseup/keyup 即時捕獲有效 Rangeavalon.contains 確保選區在編輯器內pasteHTML、現代瀏覽器用 execCommandsaveSelection,供下次操作使用這種「守衛選區」的思路,同樣適用於自定義表情、@提及、程式碼塊等所有「工具列操作 → 編輯器插入」的場景。