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

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

output in Chrome:

hey &
4条回答
  •  渐次进展
    2020-11-22 07:31

    This (live) example shows a short simple function, setCaretAtStartEnd, which takes two arguments; A (editable) node to place the caret at & a Boolean indicating where to place it (start or end of the node)

    const editableElm = document.querySelector('[contenteditable]');
    
    document.querySelectorAll('button').forEach((elm, idx) => 
      elm.addEventListener('click', () => {
        editableElm.focus()
        setCaretAtStartEnd(editableElm, idx) 
      })
    )
    
    function setCaretAtStartEnd( node, atEnd ){
      const sel = document.getSelection();
      node = node.firstChild;
    
      if( sel.rangeCount ){
          ['Start', 'End'].forEach(pos =>
            sel.getRangeAt(0)["set" + pos](node, atEnd ? node.length : 0)
          )
      }
    }
    [contenteditable]{ padding:5px; border:1px solid; }

    Place the caret anywhere


提交回复
热议问题