Contenteditable DIV - how can I determine if the cursor is at the start or end of the content

后端 未结 5 815
一整个雨季
一整个雨季 2020-12-03 02:04

I have a contenteditable div which contains typical wysiwyg editor html (bold, anchors, lists).

I need to determine if the current cursor is, onKeyDown, at the start

5条回答
  •  借酒劲吻你
    2020-12-03 02:24

    I would use a similar approach to yours except using the toString() method of Range objects rather than cloneContents() to avoid unnecessary cloning. Also, in IE < 9 (which doesn't support ranges), you can use a similar approach with the text property of TextRange.

    Note that this will have issues when there are leading and/or trailing line breaks in the content because the toString() method of a range works just like the textContent property of a node and only considers text nodes, therefore not taking into account line breaks implied by
    or block elements. Also CSS is not taken into account: for example, text inside elements that are hidden via display: none is included.

    Here's an example:

    Live demo: http://jsfiddle.net/YA3Pu/1/

    Code:

    function getSelectionTextInfo(el) {
        var atStart = false, atEnd = false;
        var selRange, testRange;
        if (window.getSelection) {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                selRange = sel.getRangeAt(0);
                testRange = selRange.cloneRange();
    
                testRange.selectNodeContents(el);
                testRange.setEnd(selRange.startContainer, selRange.startOffset);
                atStart = (testRange.toString() == "");
    
                testRange.selectNodeContents(el);
                testRange.setStart(selRange.endContainer, selRange.endOffset);
                atEnd = (testRange.toString() == "");
            }
        } else if (document.selection && document.selection.type != "Control") {
            selRange = document.selection.createRange();
            testRange = selRange.duplicate();
    
            testRange.moveToElementText(el);
            testRange.setEndPoint("EndToStart", selRange);
            atStart = (testRange.text == "");
    
            testRange.moveToElementText(el);
            testRange.setEndPoint("StartToEnd", selRange);
            atEnd = (testRange.text == "");
        }
    
        return { atStart: atStart, atEnd: atEnd };
    }
    

提交回复
热议问题