[英]How to set caret position in middle of word after regenerating innerHTML within contenteditable div
我每次擊鍵都重新生成innerHTML,以便用跨度包裝來自innerText的單詞。 我這樣做是為了搜索具有不同風格的關鍵字。
process() {
this.content.nativeElement.innerHTML = this.text.split(" ").map((word, index) => {
let wrapped;
if (this.elements.map(e => e.name).includes(word)) {
wrapped = `<span style="color: darkblue; font-weight: bold; text-decoration: underline; cursor: pointer;">${word}</span>`
} else {
wrapped = `<span style="cursor: pointer;">${word}</span>`
}
if (word === this.word) {
this.spanIndex = index;
}
return wrapped;
}).join(" ");
this.setCaretPosition();
this.addInnerHTMLListeners();
}
在 process 函數中,我設置了插入符號位置。
setCaretPosition() {
this.target.focus();
var lastNode = this.content.nativeElement.childNodes[this.nodeIndex];
var range = document.createRange();
const letterIndex = this.letterIndex;
console.log(letterIndex, lastNode.childNodes.length)
range.setStart(lastNode, letterIndex); //lastNode.childNodes.length
range.setEnd(lastNode, letterIndex);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
當光標應該在一個單詞的末尾時,它與lastNode.childNodes.length
一起使用效果很好。 但是當我處於中間時,我不知道該怎么做。 因為當我在位置 2(第三個字母)然后將它設置為 2 將導致ERROR DOMException: Failed to execute 'setStart' on 'Range': There is no child at offset 2.
我想到了。 沒有意識到 DOM 更復雜。
div 的 innerHTML 由這樣的跨度組成: <span style="color: darkblue; font-weight: bold; text-decoration: underline; cursor: pointer;">${word}</span>
我知道它是哪個跨度var node = this.content.nativeElement.childNodes[this.nodeIndex];
但是要在單詞中設置插入符號,我需要獲取它的第一個孩子,這可能是文本
var range = document.createRange();
console.log(node, node.firstChild, this.letterIndex)
range.setStart(node.firstChild, this.letterIndex);
range.setEnd(node.firstChild, this.letterIndex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.