私は、テキストを 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 私はそれについて多くのことを読みましたが、ここでかなりの量の質問を見ましたが、この特定の問題については何もありません.