setSelectionRange 适用于输入字段,但如何将光标放在可内容编辑字段的末尾?

setSelectionRange works with input fields, but how can I place the cursor at the end of a contenteditable field?

我之前问过为什么 setSelectionRange 不起作用,答案是因为它只适用于输入字段。但我想尝试使用 contenteditable 属性开发电子表格类型的页面。

window.onkeydown = function(e) {
 if (e.keyCode === 113) {
    setFocus()
 }
}


function setFocus() {
  element = document.getElementById('test')
  element.focus() // works
    .setSelectionRange(3,3) // Doesn't work
}
<div id="test" contenteditable>testing</div>
<p>Click in the Result window and then press F2.</p>

如何在用户按下 F2 后将光标置于字段末尾?

这可能是适合您的解决方案:

window.onkeydown = function(e) {
 if (e.keyCode === 113) {
    setFocus()
 }
}


function setFocus() {
  element = document.getElementById('test')
  element.focus() // works
  setCaretPosition(element,1); // Also works
}

function setCaretPosition(el, pos) {
   
  el.focus();
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(el, pos);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}
<div id="test" contenteditable>testing</div>
<p>Click in the Result window and then press F2.</p>