如何将光标移动到Chrome / Safari中可信任div中的下一个元素?

时间:2011-12-02 04:14:30

标签: javascript contenteditable cursor-position

我有逻辑在一个可信的div中插入一个标签。我想在插入后将光标设置为以下元素的开头。我必须这样做的代码是:

function insertNodeAtCaret(node) {
if(typeof window.getSelection !== 'undefined')
{
    var sel = window.getSelection();
    if(sel.rangeCount)
    {
        var rng = sel.getRangeAt(0);
        rng.collapse(false);
        rng.insertNode(node);

        // The following doesn't work in Chrome or Safari
        node = node.nextSibling;
        rng.setEndAfter(node);
        rng.setStartAfter(node);
        rng.collapse(true);
        sel.removeAllRanges();
        sel.addRange(rng);
    }
}
else if (typeof document.selection !== 'undefined' && document.selection.type !== 'Control')
{
    document.selection.createRange().pasteHTML(node.outerHTML);
}
}

然而,尽管这在IE,Opera和Firefox中完美无缺,但它在Chrome和Safari中无效。在Chrome / Safari中,光标位于跨度内文本的末尾,而不是跨度之后。即

<span>text CURSOR HERE</span>

而不是我想要的,这是:

<span>text</span>CURSOR HERE

感谢。

2 个答案:

答案 0 :(得分:2)

这是long-standing and annoying bug in WebKit。另请参阅the bug for the special case of placing the caret inside an empty inline element,其中包含更多活动。除非插入并选择单个零宽度空格字符,否则您无法做很多事情。

答案 1 :(得分:0)

您必须将contentEditable={false}赋予插入的元素:

<div contentEditable={true}> 
   <span contenEditable={false>/span>
</div>