get and set cursor position in content editable div

若如初见. 提交于 2020-11-29 19:11:18

问题


in a content editable div, i wish get and set cursor position but but without taking into account the child elements (, , etc for example).

for get, i find this solution : Get a range's start and end offset's relative to its parent container

but for set, i don't know.

please, can u help me.

thank u


回答1:


You can use rangy to define it yourself, just like this:

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

To use this function, you need to focus the editor first:

selector.focus();

Then giving an index to set cursor position:

setCaretIndex(3);

Fiddle



来源:https://stackoverflow.com/questions/59894560/get-and-set-cursor-position-in-content-editable-div

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