我正在尝试通过 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>
如何在代码标签内调整光标位置?
最佳答案
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>
关于javascript - 如何使用 Javascript 将 HTML 中的 <code> 标记中的文本末尾置于焦点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56934379/