gpt4 book ai didi

javascript - 更改内容可编辑元素的 innerHTML 后将插入符放回原处

转载 作者:太空狗 更新时间:2023-10-29 14:38:31 25 4
gpt4 key购买 nike

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

(没有 jQuery)

我不能使用 input 或 textarea 代替 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 上工作,但如果你有跨浏览器的解决方案,我也会接受。

感谢您的帮助!

最佳答案

你想多晚参加聚会?"is"

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

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

关于javascript - 更改内容可编辑元素的 innerHTML 后将插入符放回原处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21234741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com