js 内容可编辑 - 防止写入新插入的元素

js contenteditable - prevent from writing into newly inserted element

本文关键字:新插入 插入 元素 编辑 js      更新时间:2023-09-26

我正在研究一个简单的语法高亮笔,用类替换带有 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 我读了很多关于它的内容,甚至在这里看了很多问题,但没有关于这个特定问题的内容。

我假设你正在WebKit中测试这个。WebKit 的插入符号处理可防止您将插入符号放置在文本节点的开头:https://bugs.webkit.org/show_bug.cgi?id=23189。在 Firefox 中,您的代码应该没问题。

解决方法都很糟糕。一种是插入一个零宽度的空格(例如 'u200B )并选择它,但随后您必须添加特殊代码来处理箭头键和代码以删除零宽度空格。

更新

另一种解决方法是使用 WebKit 对链接有一个特殊情况,它强制插入符号在链接之后:

http://jsfiddle.net/RfMju/

因此,您可以做的(令人不快但可行的)是,当您希望插入符号进入突出显示的元素内部并将其更改为链接时,可以使用<span>