[英]Move caret to the end in contenteditable element and alight text to the end
[英]javascript: move caret to end of element (div with contenteditable)
我有這個函數用於聚焦一個有意義的div並將插入符號移到文本的末尾,但它不能按預期工作。
單擊“將插入符號移動到結尾”按鈕,插入符號位置為1而不是div#foo length。 但如果你點擊“我是一個字符串”的“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'將是'button',而不是div。
請嘗試使用此HTML:
<button onclick="moveCaretToEnd(document.getElementById('foo'))">Move caret to end</button>
編輯 :
要選擇textNode,您可以嘗試:
range.selectNodeContents(nativeElement.firstChild);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.