designMode iFrame Get Cursor Position

前端 未结 2 952
长情又很酷
长情又很酷 2021-01-06 11:53

I want to get the cursor position of an editable iFrame (using designMode). Here is the code I have so far:

document.getElementById(\'iframe_id\').contentWin         


        
相关标签:
2条回答
  • 2021-01-06 12:30

    This worked for me

    function getCaretPosition() {
    var element = document.idEditbox.document.body; // just my content IFRAME
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel, range, preCaretRange, caretOffset = 0;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        range = doc.selection.createRange();
    var tempRange = range.duplicate();
        preCaretRange = doc.body.createTextRange();
        preCaretRange.moveToElementText(element);
        preCaretRange.setEndPoint("EndToEnd", tempRange);
        caretOffset = preCaretRange.text.length;
    }
    return caretOffset;
    

    }

    0 讨论(0)
  • 2021-01-06 12:50

    The following is based on this answer but is modified to work with selections in any document (such as one in an iframe). The same caveats about the naïveté of this approach laid out in that answer still apply.

    function getCaretCharacterOffsetWithin(element) {
        var doc = element.ownerDocument || element.document;
        var win = doc.defaultView || doc.parentWindow;
        var sel, range, preCaretRange, caretOffset = 0;
        if (typeof win.getSelection != "undefined") {
            sel = win.getSelection();
            if (sel.rangeCount) {
                range = sel.getRangeAt(0);
                preCaretRange = range.cloneRange();
                preCaretRange.selectNodeContents(element);
                preCaretRange.setEnd(range.endContainer, range.endOffset);
                caretOffset = preCaretRange.toString().length;
            }
        } else if ( (sel = doc.selection) && sel.type != "Control") {
            range = doc.selection.createRange();
            preCaretRange = doc.body.createTextRange();
            preCaretRange.moveToElementText(element);
            preCaretRange.setEndPoint("EndToEnd", textRange);
            caretOffset = preCaretTextRange.text.length;
        }
        return caretOffset;
    }
    

    Example usage:

    var iframe = document.getElementById("foo");
    var iframeBody = (iframe.contentDocument || iframe.contentWindow.document).body;
    alert( getCaretCharacterOffsetWithin(iframeBody) );
    
    0 讨论(0)
提交回复
热议问题