Get contentEditable caret index position

后端 未结 10 711
暗喜
暗喜 2020-11-22 05:48

I\'m finding tons of good, crossbrowser anwers on how to SET the cursor or caret index position in a contentEditable element, but none on how to GET or find its

10条回答
  •  醉酒成梦
    2020-11-22 06:33

    As this took me forever to figure out using the new window.getSelection API I am going to share for posterity. Note that MDN suggests there is wider support for window.getSelection, however, your mileage may vary.

    const getSelectionCaretAndLine = () => {
        // our editable div
        const editable = document.getElementById('editable');
    
        // collapse selection to end
        window.getSelection().collapseToEnd();
    
        const sel = window.getSelection();
        const range = sel.getRangeAt(0);
    
        // get anchor node if startContainer parent is editable
        let selectedNode = editable === range.startContainer.parentNode
          ? sel.anchorNode 
          : range.startContainer.parentNode;
    
        if (!selectedNode) {
            return {
                caret: -1,
                line: -1,
            };
        }
    
        // select to top of editable
        range.setStart(editable.firstChild, 0);
    
        // do not use 'this' sel anymore since the selection has changed
        const content = window.getSelection().toString();
        const text = JSON.stringify(content);
        const lines = (text.match(/\\n/g) || []).length + 1;
    
        // clear selection
        window.getSelection().collapseToEnd();
    
        // minus 2 because of strange text formatting
        return {
            caret: text.length - 2, 
            line: lines,
        }
    } 
    

    Here is a jsfiddle that fires on keyup. Note however, that rapid directional key presses, as well as rapid deletion seems to be skip events.

提交回复
热议问题