简体   繁体   中英

how to get the position of the cursor in an editable div

I have the following function that tracks the cursor position in an editable div:

  function getCaretPosition(editableDiv) {
        var caretPos = 0, containerEl = null, sel, range;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.rangeCount) {
                range = sel.getRangeAt(0);
                if (range.commonAncestorContainer.parentNode == editableDiv) {
                    caretPos = range.endOffset;
                }
            }
        } else if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
            if (range.parentElement() == editableDiv) {
                var tempEl = document.createElement("span");
                editableDiv.insertBefore(tempEl, editableDiv.firstChild);
                var tempRange = range.duplicate();
                tempRange.moveToElementText(tempEl);
                tempRange.setEndPoint("EndToEnd", range);
                caretPos = tempRange.text.length;
            }
        }
        return caretPos-1;
    }

The issue is that if my editable div has the following html:

hello <span contenteditable='false'>Abderrahmane Benbachir</span>  

and I put the cursor next to the span, it starts counting the cursor from 0. Why is this? How do I fix this?

In this case, to get the caret position use this Tim Down's code instead. Which also has restoreSelection function in it which restores the caret position.

I asked the same question recently, which you can check here .

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