![](/img/trans.png)
[英]How to place the caret where it previously was after replacing the html of a contenteditable div?
[英]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.