老外可编辑div重新定位最后位置
Posted blucelee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了老外可编辑div重新定位最后位置相关的知识,希望对你有一定的参考价值。
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
以上是关于老外可编辑div重新定位最后位置的主要内容,如果未能解决你的问题,请参考以下文章
各位帅哥,jQuery怎么获取可编辑div的光标的位置或者索引? 急急急 。。。。