javascript - js contenteditable - 防止写入新插入的元素

标签 javascript selection range contenteditable

我正在开发一个简单的语法荧光笔,它用带有类的 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>

但是如果你输入,你输入的是 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..

如何解决? oO 我已经阅读了很多关于它的文章,甚至在这里看到了很多问题,但没有关于这个特定问题的内容。

最佳答案

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

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

更新

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

http://jsfiddle.net/RfMju/

所以你可以做的是使用 <span>当您希望插入符号进入突出显示的元素内并将其更改为链接时。

关于javascript - js contenteditable - 防止写入新插入的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10542769/

相关文章:

python - 如何包含大量决策循环来以正确的方式检查某个范围内的数字?

javascript - 在切换开关内添加开/关文本

javascript - 如何根据类名选择偶数或奇数元素

android - EditText setSelection 不适用于大于 8 的位置

python - 使用 Python 创建一个范围内的值依赖于另一列的列

java - 如何使用 double 格式的数字为范围之间的随机间隔编写代码?

javascript - 我需要简单的逻辑帮助来添加从 ts 文件中的模板获取的数字

javascript - ngrx : how the reducers function are invoked, 何时被调用?

SQL:假设只有两个列,如何比较不同行中的数据并仅选择唯一的 "pairs"?

VBA:按变量选择范围