我的HTML:如何設置包含文本和元素節點的組合CONTENTEDITABLE DIV的插入位置
<div id="text" contenteditable="true">abcd<img src="icon.gif"/>efgh</div>
我caret = 5;
所以我想設置插入符poisition圖像後立即爲圖像處理作爲1個字符。
所以我寫了thise代碼:
var node = document.querySelector("div");
node.focus();
var textNode = node.firstChild;
var caret = 5;
var range = document.createRange();
range.setStart(textNode, caret);
range.setEnd(textNode, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
但我得到這個錯誤:
Uncaught DOMException: Failed to execute 'setStart' on 'Range': The offset 5 is larger than or equal to the node's length (4).
請建議我如何才能實現這一目標?在我希望的插入位置之前,我可能會有幾個圖像,每個圖像將被視爲1個字符。