如何使用 Javascript 聚焦 HTML 中 <code> 标签中的文本结尾?

How to focus end of the text in <code> tag in HTML using Javascript?

我正在尝试通过 onkeypress 事件重新格式化 HTML 代码标签内的一些文本。但是在文本更改后,光标会移动到起始位置。我必须保持光标的当前位置。

为了防止这个问题,我发现了这个;

this.selectionStart = this.selectionEnd = this.value.length;

来自: Use JavaScript to place cursor at end of text in text input element

但我明白了,它只适用于输入元素:(

<code contenteditable="true" id="editor"  onkeypress="CreateStyle()">
  select * <span style="color:blue">from</span> SomeTable</code>

如何在代码标签内使用光标位置?

您可以使用Range and Selection设置选择

const codeNode = document.getElementById('editor');
const range = document.createRange();
const selection = window.getSelection();

range.setStartAfter(codeNode.lastChild);
range.setEndAfter(codeNode.lastChild);

selection.removeAllRanges();
selection.addRange(range);
<code contenteditable="true" id="editor"  onkeypress="CreateStyle()">
  select * <span style="color:blue">from</span> SomeTable</code>