How to set caret(cursor) position in contenteditable element (div)?

后端 未结 10 1519
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 01:41

I have this simple HTML as an example:

text text text
text text text
text text
10条回答
  •  花落未央
    2020-11-22 02:16

    In most browsers, you need the Range and Selection objects. You specify each of the selection boundaries as a node and an offset within that node. For example, to set the caret to the fifth character of the second line of text, you'd do the following:

    function setCaret() {
        var el = document.getElementById("editable")
        var range = document.createRange()
        var sel = window.getSelection()
        
        range.setStart(el.childNodes[2], 5)
        range.collapse(true)
        
        sel.removeAllRanges()
        sel.addRange(range)
    }
    text text text
    text text text
    text text text

    IE < 9 works completely differently. If you need to support these browsers, you'll need different code.

    jsFiddle example: http://jsfiddle.net/timdown/vXnCM/

提交回复
热议问题