码迷,mamicode.com
首页 > 其他好文 > 详细

老外可编辑div重新定位最后位置

时间:2019-12-26 09:18:37      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:remove   cat   his   code   use   overflow   lin   focus   number   

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重新定位最后位置

标签:remove   cat   his   code   use   overflow   lin   focus   number   

原文地址:https://www.cnblogs.com/BluceLee/p/12100044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!