我正在研究一種簡單的語法突出顯示器,用dom元素替換具有類的文本。js contenteditable - 防止寫入新插入的元素
說,我有一個
<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>
後,但如果你鍵入,你鍵入到span.....不管是什麼。
//型棒
<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..
如何解決呢?我已經閱讀了很多內容,甚至在這裏看到了相當多的問題,但沒有提到這個問題。
我看,是的,必須是它,因爲它似乎在壁虎上工作..謝謝你,我接受你的答案。我有點不情願使用這種解決方法,儘管現在看起來沒有其他辦法。謝謝 – tenshou
@tenshou:我發現另一個解決方法可能會更好。我更新了我的答案。 –
很好,謝謝。它確實消除了刪除零空格的額外工作。並且它看起來完全可以工作,即使點擊或使用箭頭鍵也無法輸入鏈接,而壁虎的邊界很狹窄,如果你的目標是正確的,你可以將光標放在鏈接中,或者直接放在鏈接之後,但看到這些角色仍然在相同的偏移量上。但那是另一回事。謝謝! – tenshou