富文本編輯器有個惱人的老問題:使用者點了工具列上的「插入圖片」按鈕後,編輯區就失焦了,游標位置也隨之遺失,圖片往往被插到開頭或結尾。wangEditor 之所以能在 IE6~8 上都做到「失焦後仍在原處插入」,關鍵只有一個觀念:在失焦之前先把 selection 與 range 存起來,插入前再還原。
var currentRange, _parentElem,
supportRange = typeof document.createRange === 'function';
// 取得目前的游標範圍
function getCurrentRange() {
var selection, range, txt = $('editor');
if (supportRange) {
selection = document.getSelection();
if (selection.getRangeAt && selection.rangeCount) {
range = document.getSelection().getRangeAt(0);
_parentElem = range.commonAncestorContainer;
}
} else {
range = document.selection.createRange();
_parentElem = range.parentElement();
}
// 確認游標真的在編輯區內,避免存到別處的 selection
if (_parentElem && (avalon.contains(txt, _parentElem) || txt === _parentElem)) {
return range;
}
return range;
}
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();
}
}
關鍵是必須在編輯區綁定 keyup 與 mouseup,因為這兩個時機游標位置是明確的,可以隨時更新存下來的 range:
function insertImage(html) {
restoreSelection(); // 先把游標放回原位
if (document.selection) currentRange.pasteHTML(html);
else document.execCommand("insertImage", false, html);
saveSelection(); // 插入後再存一次,方便連續插入
}
avalon.bind($('post_input'), 'mouseup', function(e) { saveSelection(); });
avalon.bind($('post_input'), 'keyup', function(e) { saveSelection(); });
這裡用的是 <div contenteditable="true"> 而非 iframe,程式碼量比 iframe 方案少很多,邏輯也一目了然。
wangEditor 原始碼統一使用 document.execCommand("insertImage", false, html),但這個方法有個問題:在 IE6/7/8 中若要一次插入多張圖片,只會在該位置插入一張,其餘的會被丟掉。
解法是分流的判斷——IE 走 currentRange.pasteHTML(html),直接插入 HTML 片段;其他瀏覽器才用 execCommand。注意此時傳入的參數不再是單純的圖片網址,而是完整的 <img> 標籤字串。
「存 range、插入前還原」這個思路至今仍然正確,值得學。但技術選擇上,document.execCommand 已被標示為 deprecated,不建議再用於新專案;IE6~8 的分流判斷也早已沒有必要。
現在要實作同樣的功能,主流做法是使用 Selection API 搭配 Range.insertNode():把要插入的內容建成節點,直接插入到儲存下來的 range 位置,再把游標移到插入內容之後。這樣不必經過 execCommand,行為更可控。
更實際的建議是:除非有特殊的客製需求,否則直接使用 ProseMirror、Slate、TipTap 或 Lexical 這類現代編輯器框架,游標保持、undo/redo、協作編輯等問題都已經被處理好了,自己刻一個的維護成本遠比想像中高。