gpt4 book ai didi

javascript - 如何在 contenteditable 元素中保持插入符号的位置

转载 作者:行者123 更新时间:2023-11-27 22:49:26 25 4
gpt4 key购买 nike

我怎样才能保持插入符号在 contenteditable 元素中的位置,当我尝试更新可编辑元素的 innerHTML 插入符号位置跳转到第一行时,我需要一个函数可以更新或更改可编辑元素 innerHTML 时保持插入符号的位置,谢谢。

我的代码:

// content editable element
let editor = document.getElementById("editor");

editor.onkeypress = (e) => {
if (e.keyCode === 32) {
let lines = editor.children;
for (let line of lines) {
line.innerHTML += "Hello World !!!";
}
}
}

最佳答案

我的回答:

// content editable element
let editor = document.getElementById("editor");

// on keypress
editor.onkeypress = () => {
// get the position of caret
let pos = getCaretPos(editor.children[0]);

// update the innerHTML
editor.children[0].innerHTML += "Hello World !!!";

// set the caret position
setCaretPos(editor.children[0], pos);
}

function getCaretPos(element) {
var ie = (typeof document.selection != "undefined" && document.selection.type != "Control") && true;
var w3 = (typeof window.getSelection != "undefined") && true;
var caretOffset = 0;
if (w3) {
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
} else if (ie) {
var textRange = document.selection.createRange();
var preCaretTextRange = document.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}

function setCaretPos(element, position) {
var node = element;
node.focus();
var textNode = node.firstChild;
var caret = position; // insert caret after the 10th character say
var range = document.createRange();
range.setStart(textNode, caret);
range.setEnd(textNode, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}

关于javascript - 如何在 contenteditable 元素中保持插入符号的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59521466/

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