我发现此脚本可以在未聚焦时并通过按一个按钮来恢复内容可编辑元素中的插入符号位置。因此,每件事都很正常,但是如果我按Enter键或执行
换行符或结束于另一行的插入符号,则脚本无法在新行上找到插入符号的位置。这就是我的意思。例如,我在 go 之后恢复插入符号的位置。
Today was a good day.
但是如果它在另一行上则不起作用。
Today was
a good day.
那么无论该contenteditable元素中的位置如何,我如何都能使该脚本在任何行上工作?
代码
document.addEventListener('DOMContentLoaded',function(){
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != 'undefined') {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ((sel = doc.selection) && sel.type != 'Control') {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint('EndToEnd', textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
var lastCaretPos = 14;
function showCaretPos() {
/* You could store the position when you call this function */
var el = document.querySelector('#test');
lastCaretPos = getCaretCharacterOffsetWithin(el);
var caretPosEl = document.querySelector('#caretPos');
caretPosEl.innerHTML = 'Caret position: ' + lastCaretPos;
}
function restoreCaretPos() {
var node = document.querySelector('#test');
node.focus();
var textNode = node.firstChild;
var range = document.createRange();
range.setStart(textNode, lastCaretPos);
range.setEnd(textNode, lastCaretPos);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
document.querySelector('#test').onkeyup = showCaretPos;
document.querySelector('#test').onmouseup = showCaretPos;
document.querySelector('#button').onclick = restoreCaretPos;
});
<div id='test' contenteditable='true'>Today was a good day.</div>
<div id='caretPos'>Caret position: 14</div>
<input type='button' id='button' value='restore caret'>