如何将光标移动到Chrome / Safari中可信任div中的下一个元素? [英] How do you move the cursor to the next element in a contenteditable div in Chrome/Safari?

查看:123
本文介绍了如何将光标移动到Chrome / Safari中可信任div中的下一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

谢谢。

推荐答案

这是 WebKit中长期存在且烦人的错误。另请参见将插入符号放入空内联元素的特殊情况的错误 ,有更多的活动。除非插入并选择单个零宽度空格字符,否则您无法做很多事情。

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.

这篇关于如何将光标移动到Chrome / Safari中可信任div中的下一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆