contenteditable, set caret at the end of the text (cross-browser)

前端 未结 4 1840
小鲜肉
小鲜肉 2020-11-22 06:56

output in Chrome:

hey &
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 07:50

    The following function will do it in all major browsers:

    function placeCaretAtEnd(el) {
        el.focus();
        if (typeof window.getSelection != "undefined"
                && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(false);
            textRange.select();
        }
    }
    
    placeCaretAtEnd( document.querySelector('p') );
    p{ padding:.5em; border:1px solid black; }

    foo bar

    Placing the caret at the start is almost identical: it just requires changing the Boolean passed into the calls to collapse(). Here's an example that creates functions for placing the caret at the start and at the end:

    function createCaretPlacer(atStart) {
        return function(el) {
            el.focus();
            if (typeof window.getSelection != "undefined"
                    && typeof document.createRange != "undefined") {
                var range = document.createRange();
                range.selectNodeContents(el);
                range.collapse(atStart);
                var sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (typeof document.body.createTextRange != "undefined") {
                var textRange = document.body.createTextRange();
                textRange.moveToElementText(el);
                textRange.collapse(atStart);
                textRange.select();
            }
        };
    }
    
    var placeCaretAtStart = createCaretPlacer(true);
    var placeCaretAtEnd = createCaretPlacer(false);
    

提交回复
热议问题