Set focus on div contenteditable element

后端 未结 9 2079
深忆病人
深忆病人 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:19

    Old post but none of the solutions worked for me. I figured it out eventually though:

    var div = document.getElementById('contenteditablediv');
    setTimeout(function() {
        div.focus();
    }, 0);
    
    0 讨论(0)
  • 2020-11-29 02:31

    In modern browsers you can use:

    var p = document.getElementById('contentEditableElementId'),
        s = window.getSelection(),
        r = document.createRange();
    r.setStart(p, 0);
    r.setEnd(p, 0);
    s.removeAllRanges();
    s.addRange(r);
    

    But if your element is empty I got some strange problems so for empty elements you can do this:

    var p = document.getElementById('contentEditableElementId'),
        s = window.getSelection(),
        r = document.createRange();
    p.innerHTML = '\u00a0';
    r.selectNodeContents(p);
    s.removeAllRanges();
    s.addRange(r);
    document.execCommand('delete', false, null);
    

    After deleting nbsp cursor stays inside p element

    P.S. just ordinary space doesn't work for me

    0 讨论(0)
  • 2020-11-29 02:31

    You can try this code, it can auto focus in your last insert location.

    let p = document.getElementById('contenteditablediv')
    let s = window.getSelection()
    let r = document.createRange()
    r.setStart(p, p.childElementCount)
    r.setEnd(p, p.childElementCount)
    s.removeAllRanges()
    s.addRange(r)
    
    0 讨论(0)
提交回复
热议问题