获取和设置光标在内容中的位置可编辑 div

get and set cursor position in content editable div

在可编辑的内容 div 中,我希望获取并设置光标位置,但不考虑子元素(, 等等).

对于 get,我找到了这个解决方案:Get a range's start and end offset's relative to its parent container

但是对于集合,我不知道。

拜托,你能帮帮我吗

谢谢你

你可以用rangy自己定义,就像这样:

var selector = document.querySelector('[contenteditable]');

var setCaretIndex = function (index) {
    var charIndex = 0, stop = {};

    var traverseNodes = function (node) {
        if (node.nodeType === 3) {
            var nextCharIndex = charIndex + node.length;
            if (index >= charIndex && index <= nextCharIndex) {
                rangy.getSelection().collapse(node, index - charIndex);
                throw stop;
            }
            charIndex = nextCharIndex;
        }

        // Count an empty element as a single character. The list below may not be exhaustive.
        else if (node.nodeType === 1 && /^(input|br|img|col|area|link|meta|link|param|base)$/i.test(node.nodeName)) {
            charIndex += 1;
        } else {
            var child = node.firstChild;
            while (child) {
                traverseNodes(child);
                child = child.nextSibling;
            }
        }
    };

    try {
        traverseNodes(selector);
    } catch (ex) {
        if (ex !== stop) throw ex;
    }
};

要使用此功能,您需要先关注编辑器:

selector.focus();

然后给出一个索引来设置光标位置:

setCaretIndex(3);

Fiddle