How do you move the cursor to the next element in

2019-07-07 01:40发布

问题:

I have logic to insert a tag in a contenteditable div. I want to set the cursor to the start of the following element after the insertion. The code I have to do this is:

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);
}
}

However though this works perfectly in IE, Opera and Firefox it doesn't work in Chrome and Safari. In Chrome/Safari the cursor is placed at the end of the text within the span, rather than after the span. ie

<span>text CURSOR HERE</span>

instead of what I am wanting, which is:

<span>text</span>CURSOR HERE

Thanks.

回答1:

This is a long-standing and annoying bug in WebKit. See also the bug for the special case of placing the caret inside an empty inline element, which has more activity. There's not a lot you can do about it, unless inserting and selecting a single zero-width space character is acceptable.