按键事件发生后如何获取文本光标位置? [英] How to get text cursor position after keypress event happened?
问题描述
我正在写一个语法荧光笔。荧光笔应该在输入文本时立即更新突出显示并使用箭头键导航。
I am writing a syntax highlighter. The highlighter should update the highlighting immediately while entering text and navigating with the arrow keys.
我遇到的问题是当'keypress'事件被触发时,你仍然通过 window.getSelection()
获取文本光标的旧位置。
The problem I'm facing is that when the 'keypress' event is fired, you still get the old position of the text cursor via window.getSelection()
.
示例:
function handleKeyEvent(evt) {
console.log(evt.type, window.getSelection().getRangeAt(0).startOffset);
}
var div = document.querySelector("div");
div.addEventListener("keydown", handleKeyEvent);
div.addEventListener("keypress", handleKeyEvent);
div.addEventListener("input", handleKeyEvent);
div.addEventListener("keyup", handleKeyEvent);
<div contenteditable="true">f<span class="highlight">oo</span></div>
在示例中,将插入符号放在单词foo之前,然后按→(右箭头键)。
In the example, place the caret before the word 'foo', then press → (the Right Arrow key).
在控制台中你最喜欢的DevTool你会看到以下内容:
Within the console of your favorite DevTool you'll see the following:
keydown 0
keypress 0
keyup 1
0
除了 keypress
显然是旧的插入位置。如果你再按下→,你会得到类似的结果:
That 0
besides keypress
is obviously the old caret position. If you hold down → a bit longer, you'll get something like this:
keydown 0
keypress 0
keydown 1
keypress 1
keydown 1
keypress 1
keydown 2
keypress 2
keyup 2
我想得到的是新的插入位置,就像我为'keyup'或'input'获得它一样。虽然'keyup'被触发得太晚了(我想在按下键时突出显示语法)并且'input'仅在实际有一些输入时被触发(但是→不产生任何输入输入)。
What I want to get is the new caret position like I would get it for 'keyup' or 'input'. Though 'keyup' is fired too late (I want to highlight the syntax while the key is pressed down) and 'input' is only fired when there is actually some input (but → doesn't produce any input).
是否有一个事件在插入符号位置发生变化后触发而不仅仅是输入?或者我是否必须计算文本光标的位置,如果是,如何计算? (我假设当文本换行并按↓(向下箭头键)时,这会变得非常复杂。)
Is there an event that is fired after the caret position has changed and not only on input? Or do I have to calculate the position of the text cursor and if so, how? (I assume this can get quite complicated when the text wraps and you press ↓ (the Down Arrow key).)
推荐答案
您可以使用 setTimeout
异步处理 keydown
事件:
You can use setTimeout
to process the keydown
event asynchronously:
function handleKeyEvent(evt) {
setTimeout(function () {
console.log(evt.type, window.getSelection().getRangeAt(0).startOffset);
}, 0);
}
var div = document.querySelector("div");
div.addEventListener("keydown", handleKeyEvent);
<div contenteditable="true">This is some text</div>
该方法解决了关键处理问题。在您的示例中,您还在 div
中包含 span
元素,这会改变由返回的位置值
That method addresses the key processing problem. In your example, you also have a span
element inside of the div
, which alters the position value returned by
window.getSelection().getRangeAt(0).startOffset
这篇关于按键事件发生后如何获取文本光标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!