简体   繁体   中英

How to set caret position in contenteditable with childs nodes?

I have this code (he is not correct, but this gives an idea) :

function setCaret(contentEditable, pos) {
    if (contentEditable.hasChildNodes()) {
        var
            nodes = contentEditable.childNodes,
            pos2 = 0,
            cpt = 0,
            nb = nodes.length,
            node;

        for (cpt; cpt < nb && pos2 < pos; cpt++) {
            node = nodes[cpt];
            if (node.nodeType === 3) {
                pos2 += node.length;
            } else {
                pos2 += node.textContent.length;
            }
        }

        var textNode; 
        if (pos2 <= pos) {
            textNode = contentEditable.childNodes[cpt];
            pos = pos - pos2;
        } else {
            textNode = contentEditable.childNodes[cpt-1];
        }

        var range = document.createRange();
        range.setStart(textNode, pos);
        range.setEnd(textNode, pos);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
}

The idea is to find the position of the good node based on the given position.

Example (pipe is the caret):

Some bold |text. 粗体 |文本。

  • set position = 14
  • 5 nodes [#text, b, #text, b, #text]
  • node with caret (index of nodes) = 4
  • start position for node 4 : 13
  • 14 - 13 = 1

range.setStart(nodes[4], 1);

How to work my code in all cases please (javascript only (without library), IE optional) ? Perhaps a simpler solution exists ?

(JSFiddle test : https://jsfiddle.net/mg4mm528/ )

With the help of execCommand you can achieve your goal.

document.execCommand ('bold', false, null);

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM