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

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

output in Chrome:

hey &
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 07:40

    If you are using the google closure compiler, you can do the following (somewhat simplified from Tim's answer):

    function placeCaretAtEnd(el) {
        el.focus();
        range = goog.dom.Range.createFromNodeContents(el);
        range.collapse(false);
        range.select();
    }
    

    Here's the same thing in ClojureScript:

    (defn place-caret-at-end [el] 
       (.focus el)
       (doto (.createFromNodeContents goog.dom.Range el)
             (.collapse false)
             .select))
    

    I have tested this in Chrome, Safari and FireFox, not sure about IE...

提交回复
热议问题