我有这个函数来聚焦一个内容可编辑的div并将插入符号移动到文本的末尾,但它没有按预期工作。
单击按钮"将插入符号移动到末尾",插入符号位置为 1 而不是div#foo 长度。但是如果你点击"I'm a string"的"g"字符,插入符号位置是 12
function moveCaretToEnd(nativeElement) {
nativeElement.focus();
if (window.getSelection) {
if (typeof window.getSelection !== 'undefined' && typeof document.createRange !== 'undefined') {
const range = document.createRange();
range.selectNodeContents(nativeElement.firstChild);
range.collapse(false);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
updateCaretPos(window.getSelection().anchorOffset);
}
function updateCaretPos(pos){
document.getElementById('caretpos').innerHTML = pos;
}
<div id="foo" contenteditable="true" onclick="updateCaretPos(window.getSelection().anchorOffset)" style="border: 1px solid grey">i'm a string</div>
<p>Caret position <div id="caretpos"></div></p>
<button onclick="moveCaretToEnd(document.getElementById('foo'))">Move caret to end</button>
您正在尝试将按钮本身作为显示插入符号的元素传递,我建议您执行以下操作:
function moveCaretToEnd(nativeElement) {
// If nothing passed, choose an element by default
nativeElement = nativeElement || document.getElementById('foo');
nativeElement.focus();
if (window.getSelection) {
if (typeof window.getSelection !== 'undefined' && typeof document.createRange !== 'undefined') {
const range = document.createRange();
range.selectNodeContents(nativeElement);
range.collapse(false);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
updateCaretPos();
}
function updateCaretPos(){
document.getElementById('caretpos').innerHTML = window.getSelection().anchorOffset;
}
moveCaretToEnd(document.getElementById('foo'));
在 HTML 方面,我在按钮上添加了type="button"
,因此它不会提交:
<div id="foo" contenteditable="true" onclick="updateCaretPos()">click me</div>
<p>Caret position <div id="caretpos"></div></p>
<button type="button" onclick="moveCaretToEnd()">Move caret to end</button>
你将"this"传递给函数,但"this"将是"按钮",而不是div。
试试这个html:
<button onclick="moveCaretToEnd(document.getElementById('foo'))">Move caret to end</button>
编辑:
要选择 textNode,您可以尝试:
range.selectNodeContents(nativeElement.firstChild);