Set focus on div contenteditable element

后端 未结 9 2120
深忆病人
深忆病人 2020-11-29 01:51

I have a

where I define by a WYSIWYG some elements. For example

,

, etc. I would l

9条回答
  •  伪装坚强ぢ
    2020-11-29 02:08

    To build further on @Surmon answer. If you are looking to auto focus right after your last letter/number in the text instead of the last insertion location (last insertion location will move the cursor to a new line if the child nodes are enclosed in block type tags and not plain text) then apply this small modification:

    r.setStart(p.lastChild, 1);
    r.setEnd(p.lastChild, 1);
    

    This is an extended function that checks if the editor/element has any child nodes and depending on the situation sets the cursor accordingly at the end:

    let p = document.getElementById('contenteditablediv');
    p.focus();  // alternatively use setTimeout(() => { p.focus(); }, 0);
    // this is enough to focus an empty element (at least in Chrome)
    
    if (p.hasChildNodes()) {  // if the element is not empty
      let s = window.getSelection();
      let r = document.createRange();
      let e = p.childElementCount > 0 ? p.lastChild : p;  
      r.setStart(e, 1); 
      r.setEnd(e, 1);    
      s.removeAllRanges();
      s.addRange(r);
    } 
    

提交回复
热议问题