Set cursor position on contentEditable

后端 未结 8 2136
悲&欢浪女
悲&欢浪女 2020-11-22 09:05

I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable=\'on\'

regains focus. It appears
8条回答
  •  难免孤独
    2020-11-22 09:52

    I had a related situation, where I specifically needed to set the cursor position to the END of a contenteditable div. I didn't want to use a full fledged library like Rangy, and many solutions were far too heavyweight.

    In the end, I came up with this simple jQuery function to set the carat position to the end of a contenteditable div:

    $.fn.focusEnd = function() {
        $(this).focus();
        var tmp = $('').appendTo($(this)),
            node = tmp.get(0),
            range = null,
            sel = null;
    
        if (document.selection) {
            range = document.body.createTextRange();
            range.moveToElementText(node);
            range.select();
        } else if (window.getSelection) {
            range = document.createRange();
            range.selectNode(node);
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        }
        tmp.remove();
        return this;
    }
    

    The theory is simple: append a span to the end of the editable, select it, and then remove the span - leaving us with a cursor at the end of the div. You could adapt this solution to insert the span wherever you want, thus putting the cursor at a specific spot.

    Usage is simple:

    $('#editable').focusEnd();
    

    That's it!

提交回复
热议问题