如何知道按键事件中按下的按键在字符串中的具体位置

Ric*_*cky 1 javascript keypress onkeypress typescript

我不知道是否可能,但我需要知道使用 javascript 输入字符的具体位置。例如:

我有:162345.25,如果我想输入另外6个数字,在三到四个数字之间(1623 6 45.25),我需要知道在哪个位置输入(在本例中是第五个位置)。

我的问题是我需要知道在“按键”事件中我只能捕获按下的按键。有人知道这是否可能?

jun*_*var 6

let x = document.getElementById('x');
x.addEventListener('keypress', () => console.log(x.selectionStart));
Run Code Online (Sandbox Code Playgroud)
<input id='x'>
Run Code Online (Sandbox Code Playgroud)

按键事件不会知道光标位置。但如果您有感兴趣的特定元素,则可以获得element.selectionStart.