繁体   English   中英

更改 contenteditable 元素的 innerHTML 后,将插入符号放回原来的位置

[英]Place caret back where it was after changing innerHTML of a contenteditable element

我需要在每次击键后在 JavaScript 中更新 contenteditable P 元素的 innerHTML

(没有 jQuery)

我不能使用输入或文本区域来代替 P 元素。

它工作得很好,但是当 innerHTML 被重置时,插入符号总是回到段落的开头。

我尝试使用其他关于插入符号和 contenteditable 的 SO 问题的解决方案,但在我的情况下似乎不起作用:我想将插入符号放回更新 innerHTML 之前的确切位置。

 p.oninput=function(){ // Get caret position c = window.getSelection(). getRangeAt(0). startOffset; console.log(c); // Update innerHTML p.innerHTML = p.innerHTML.toUpperCase(); // Place caret back // ??? }
 p{ border: 1px dotted red }
 <p contenteditable id=p>type here

顺便说一句,它不需要在 IE 上工作,但如果你有跨浏览器的解决方案,我也会接受。

谢谢你的帮助!

考虑逐步摆脱问题。

解决方案1:在完成输入之前不要转换为大写。

解决方案2:将P设置为等宽字体。 使P透明。 将值更新后面的div作为大写。 不知道如何显示插入符号?

记得在大约一年前看到文章,其中编码界面使用类似的方法在textarea中使用颜色编码的代码。

我补充道

const range = window.getSelection();
range.selectAllChildren(p);
range.collapseToEnd();

你的代码似乎解决了问题。

 p.oninput=function(){ // Get caret position c = window.getSelection(). getRangeAt(0). startOffset; console.log(c); // Update innerHTML p.innerHTML = p.innerHTML.toUpperCase(); const range = window.getSelection(); range.selectAllChildren(p); range.collapseToEnd(); } 
 p{ border: 1px dotted red } 
 <p contenteditable id=p>type here 

你想多晚参加聚会? “是的”

如果有人仍在寻找解决方案,也许这对您有用?

 p.oninput=function(){ // Get caret position c = window.getSelection(). getRangeAt(0). startOffset; console.log(c); // Update innerHTML p.innerHTML = p.innerHTML.toUpperCase(); var range = document.createRange(); var sel = window.getSelection(); range.setStart(p.childNodes[0], c); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); }
 p{ border: 1px dotted red }
 <p contenteditable id=p>type here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM