javascript:将插入符号移动到元素的末尾(带contenteditable的div)

javascript:将插入符号移动到元素的末尾(带contenteditable的div),javascript,Javascript,我有这个功能来聚焦contenteditable div,并将插入符号移动到文本的末尾,但它没有按预期工作 单击“将插入符号移动到末端”按钮,插入符号位置为1,而不是div#foo length。但是如果单击“我是字符串”的“g”字符,插入符号的位置是12 函数MoveCareToEnd(nativeElement){ nativeElement.focus(); if(window.getSelection){ if(typeof window.getSelection!=“未定义”&&ty

我有这个功能来聚焦contenteditable div,并将插入符号移动到文本的末尾,但它没有按预期工作

单击“将插入符号移动到末端”按钮,插入符号位置为1,而不是div#foo length。但是如果单击“我是字符串”的“g”字符,插入符号的位置是12

函数MoveCareToEnd(nativeElement){
nativeElement.focus();
if(window.getSelection){
if(typeof window.getSelection!=“未定义”&&typeof document.createRange!=“未定义”){
常量范围=document.createRange();
range.selectNodeContents(nativeElement.firstChild);
范围。塌陷(假);
const sel=window.getSelection();
选择removeAllRanges();
选择添加范围(范围);
}
}
UpdateCartPos(window.getSelection().AnchoroOffset);
}
函数updateCartPOS(pos){
document.getElementById('caretpos')。innerHTML=pos;
}
我是一个字符串
插入符号位置


将插入符号移动到末尾
如果您试图将按钮本身作为插入符号显示的元素传递,我建议您执行以下操作:

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>

什么不能“如预期”工作?它能做什么,你期望什么?@PoulBak right!我已经更新了问题…当你点击文本时,“anchorNode”从“foo”变为textnode,因此anchorOffset变为12。(选择非常混乱)。这是因为它是'foo'的第一个子节点。
range.selectNodeContents(nativeElement.firstChild);