如何在每次按键时更改
我更改 innerHTML 的原因是 添加了
我暂时使用 StackOverflow 答案中的以下代码作为临时方法,但它有一个重大的漏洞。如果按下回车键,则光标停留在旧位置或跳到随机位置。这是因为算法计算光标从开头算起的字符数,但它不将 HTML 标记或换行符视为字符。richTextBox 插入
修复思路:
<div id="richTextBox" contenteditable="true"></div>
的 innerHTML 时,保持光标位置不变?替换 innerHTML 会破坏光标位置。我更改 innerHTML 的原因是 添加了
<span>
标签, 这是代码高亮程序的一部分。Span 标签允许我放置正确的颜色高亮显示。我暂时使用 StackOverflow 答案中的以下代码作为临时方法,但它有一个重大的漏洞。如果按下回车键,则光标停留在旧位置或跳到随机位置。这是因为算法计算光标从开头算起的字符数,但它不将 HTML 标记或换行符视为字符。richTextBox 插入
<br>
来创建换行符。修复思路:
- 修复以下代码? 请参见Fiddle
- 用更简单的代码替换?我尝试过很多简单的东西,涉及
window.getSelection()
和document.createRange()
,但我无法使它们正常工作。 - 替换没有此错误的 richTextBox 库或模块?
截图
// Credit to Liam (Stack Overflow)
// https://dev59.com/Jm025IYBdhLWcg3wCxVN#41034697
class Cursor {
static getCurrentCursorPosition(parentElement) {
var selection = window.getSelection(),
charCount = -1,
node;
if (selection.focusNode) {
if (Cursor._isChildOf(selection.focusNode, parentElement)) {
node = selection.focusNode;
charCount = selection.focusOffset;
while (node) {
if (node === parentElement) {
break;
}
if (node.previousSibling) {
node = node.previousSibling;
charCount += node.textContent.length;
} else {
node = node.parentNode;
if (node === null) {
break;
}
}
}
}
}
return charCount;
}
static setCurrentCursorPosition(chars, element) {
if (chars >= 0) {
var selection = window.getSelection();
let range = Cursor._createRange(element, { count: chars });
if (range) {
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
static _createRange(node, chars, range) {
if (!range) {
range = document.createRange()
range.selectNode(node);
range.setStart(node, 0);
}
if (chars.count === 0) {
range.setEnd(node, chars.count);
} else if (node && chars.count >0) {
if (node.nodeType === Node.TEXT_NODE) {
if (node.textContent.length < chars.count) {
chars.count -= node.textContent.length;
} else {
range.setEnd(node, chars.count);
chars.count = 0;
}
} else {
for (var lp = 0; lp < node.childNodes.length; lp++) {
range = Cursor._createRange(node.childNodes[lp], chars, range);
if (chars.count === 0) {
break;
}
}
}
}
return range;
}
static _isChildOf(node, parentElement) {
while (node !== null) {
if (node === parentElement) {
return true;
}
node = node.parentNode;
}
return false;
}
}
window.addEventListener('DOMContentLoaded', (e) => {
let richText = document.getElementById('rich-text');
richText.addEventListener('input', function(e) {
let offset = Cursor.getCurrentCursorPosition(richText);
// Pretend we do stuff with innerHTML here. The innerHTML will end up getting replaced with slightly changed code.
let s = richText.innerHTML;
richText.innerHTML = "";
richText.innerHTML = s;
Cursor.setCurrentCursorPosition(offset, richText);
richText.focus(); // blinks the cursor
});
});
body {
margin: 1em;
}
#rich-text {
width: 100%;
height: 450px;
border: 1px solid black;
cursor: text;
overflow: scroll;
resize: both;
/* in Chrome, must have display: inline-block for contenteditable=true to prevent it from adding <div> <p> and <span> when you type. */
display: inline-block;
}
<p>
Click somewhere in the middle of line 1. Hit enter. Start typing. Cursor is in the wrong place.
</p>
<p>
Reset. Click somewhere in the middle of line 1. Hit enter. Hit enter again. Cursor goes to some random place.
</p>
<div id="rich-text" contenteditable="true">Testing 123<br />Testing 456</div>
浏览器
Windows 7, Google Chrome v83
$(selector).text()
这样的解析器来代替innerHTML
?它会去掉标签。使用它可能会避免尝试计算你插入或删除了多少个标签的头痛... 它只会提供文本内容,而不是HTML的长度。 - joshstrike