【问题标题】:js contenteditable - prevent from writing into newly inserted elementjs contenteditable - 防止写入新插入的元素
【发布时间】:2012-05-10 22:00:24
【问题描述】:

我正在开发一个简单的语法荧光笔,它用类替换带有 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 我已经阅读了很多关于它的内容,甚至在这里查看了很多问题,但没有关于这个特定问题。

【问题讨论】:

    标签: javascript selection range contenteditable


    【解决方案1】:

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

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

    更新

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

    http://jsfiddle.net/RfMju/

    因此,您可以做的是,当您希望插入符号进入突出显示的元素并将其更改为链接时,使用&lt;span&gt;,这是不愉快但可行的。

    【讨论】:

    • 我明白了,是的,一定是这样,因为它似乎对壁虎有效。谢谢,我接受你的回答。我有点不愿意使用这样的解决方法,尽管目前似乎没有其他方法。谢谢
    • @tenshou:我发现了另一种可能更好的解决方法。我更新了我的答案。
    • 很好,谢谢。它确实消除了删除带空格的零的额外工作。它似乎绝对有效,即使单击或使用箭头键,您也无法输入链接,而壁虎的边界很窄,如果您瞄准正确,您可以将光标放在链接中,或者就在它之后,但看到字符它仍然会在相同的偏移量上。但那是另一回事了。谢谢!
    • 这还能用吗?我正在运行小提琴,但我可以输入链接文本并进行编辑。
    猜你喜欢
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多