Javascript, key press value is always one characte

2020-02-01 18:10发布

If I type 'St', by the time I press the t, if I output the input of textfield.value in the onkeypress/onkeydown functions, I only get 'S'.

Why is this? How do I get rid of this lag?

3条回答
够拽才男人
2楼-- · 2020-02-01 18:42

Because the keystroke is not registered until keyup event occurs. So you should detect onkeyup event instead of onkeypress.

查看更多
霸刀☆藐视天下
3楼-- · 2020-02-01 18:47

Within the keypress event, it's still possible to prevent the typed character from registering, so the input's value canot be updated until after the keypress event. You can use the keyup event instead, or use window.setTimeout() to set up a delay.

查看更多
smile是对你的礼貌
4楼-- · 2020-02-01 18:55

use the keyup event instead of keypress. keydown will show the before-keystroke value, as will keypress (apparently).

查看更多
登录 后发表回答