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)
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);
} 转载:https://stackoverflow.com/questions/2388164/set-focus-on-div-contenteditable-element
来源:https://www.cnblogs.com/BluceLee/p/12100044.html