How do you move the cursor to the next element in a contenteditable div in Chrome/Safari?

走远了吗. 提交于 2019-12-10 18:52:22

问题


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.




回答2:


You have to give contentEditable={false} to the element you inserted :

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


来源:https://stackoverflow.com/questions/8351714/how-do-you-move-the-cursor-to-the-next-element-in-a-contenteditable-div-in-chrom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!