[英]Place caret back where it was after changing innerHTML of a contenteditable element
I need to update the innerHTML of a contenteditable P element after each keystroke, in JavaScript我需要在每次击键后在 JavaScript 中更新 contenteditable P 元素的 innerHTML
(no jQuery) (没有 jQuery)
I can't use an input or textarea instead of the P element.我不能使用输入或文本区域来代替 P 元素。
It works fine, but the caret always goes back at the beginning of the paragraph when the innerHTML is reset.它工作得很好,但是当 innerHTML 被重置时,插入符号总是回到段落的开头。
I tried to use the solutions of the other SO questions that talk about carets and contenteditable but it doesn't seem to work in my case: I want to put the caret back exactly where it was before the update of 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
BTW, It doesn't need to work on IE, but if you have a cross-browser solution, I'll take it too.顺便说一句,它不需要在 IE 上工作,但如果你有跨浏览器的解决方案,我也会接受。
Thanks for your help!谢谢你的帮助!
Consider stepping away from the problem. 考虑逐步摆脱问题。
Solution 1: do not convert to uppercase until finished typing. 解决方案1:在完成输入之前不要转换为大写。
Solution 2: set P to monospaced font. 解决方案2:将P设置为等宽字体。 Make the P transparent.
使P透明。 Have div behind that updates with values as uppercase.
将值更新后面的div作为大写。 Not sure how to show caret ... ?
不知道如何显示插入符号?
Remember seeing article a year or so ago where a coding interface used similar method to have colour coded code in a textarea. 记得在大约一年前看到文章,其中编码界面使用类似的方法在textarea中使用颜色编码的代码。
I added 我补充道
const range = window.getSelection();
range.selectAllChildren(p);
range.collapseToEnd();
to your code and it seems solve the problem. 你的代码似乎解决了问题。
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
How late do you want to be to the party?你想多晚参加聚会? "Yes"
“是的”
If someone is still looking for a solution, maybe this works for you?如果有人仍在寻找解决方案,也许这对您有用?
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.