我正在研究一个简单的语法荧光笔,用类替换带有 dom 元素的文本。
说,我有一个
<div contenteditable="true">
Some text. | And some other text.
</div>
光标位于 | 管道
//如果用户输入foo
<div contenteditable="true">
Some text. foo| And some other text.
</div>
// 然后我替换它,然后在插入的元素之后设置选择
<div contenteditable="true">
Some text. <span class="highlight-foo">foo</span>| And some other text.
</div>
但如果你输入,你输入跨度..无论如何。
//类型条
<div contenteditable="true">
Some text. <span class="highlight-foo">foobar|</span> And some other text.
</div>
我不希望这样,但我不能在新插入的元素之后设置选择。
<div contenteditable="true">
Some text. <span class="highlight-foo">foo</span>bar| And some other text.
</div>
这是执行突出显示和替换的js..
...
// chunk is the variable that holds foo, if we stick the the above example..
// select it
range.setStart(range.startContainer, range.startOffset-chunk.length);
// add it to the range
sel.addRange(range);
// replace it..then set the range to the textNode after the span
// because after the injection selection.anchorNode is the textNode inside the span..
// in chrome, however, this below sets the range correctly.
range.setStart(sel.anchorNode.parentNode.nextSibling, 0);
// and it's all good until now, but adding the range to the selection does nothing..
sel.removeAllRanges();
sel.addRange(range)
// the selection is still inside the span..
如何解决?oO 我已经阅读了很多关于它的内容,甚至在这里查看了很多问题,但没有关于这个特定问题的内容。