首先,它们具有不同的含义:它们开火:
- KeyDown – when a key was pushed down
- KeyUp – when a pushed button was released, and after the value of input/textarea is updated (the only one among these)
- KeyPress – between those and doesn t actually mean a key was pushed and released (see below). Not only it has inconsistent semantics, it was deprecated, so one shouldn t probably use it (see also this summary)
第二,一些关键人物向其中一些事件开火,不向其他事件发射<>。 例如,
- KeyPress ignores delete, arrows, PgUp/PgDn, home/end, ctrl, alt, shift etc while KeyDown and KeyUp don t (see details about esc below);
- when you switch window via alt+tab in Windows, only KeyDown for alt fires because window switching happens before any other event (and KeyDown for tab is prevented by system, I suppose, at least in Chrome 71).
此外,您应铭记,event.keyCode
(and event.
)对KitDown和KuiUp通常具有相同价值,但对于Press而言,则有所不同。 Try the playground 我创造了机会。 顺便提一下:在 Chrome,当我新闻ctrl+a和input
//<>>上,对于带有<条码>的火力(和<条码>.keyCode
(及<条码>>>>>)等于<1条码/条/条码>! (当投入不是空的时,它根本就没有火灾。)
注:这些日,使用<代码>event.key和event.code
,是最佳选择,因为它在浏览器、投放器和活动(法克)方面是标准化的,而和event.keyCode
>>>>s deprecated (。
最后,有pragmatics:
- For handling arrows, you ll probably need to use onKeyDown: if user holds ↓, KeyDown fires several times (while KeyUp fires only once when they release the button). Also, in some cases you can easily prevent propagation of KeyDown but can t (or can t that easily) prevent propagation of KeyUp (for instance, if you want to submit on enter without adding newline to the text field).
- Suprisingly, when you hold a key, say in
textarea
, both KeyPress and KeyDown fire multiple times (Chrome 71), I d use KeyDown if I need the event that fires multiple times and KeyUp for single key release.
- KeyDown is usually better for games when you have to provide better responsiveness to their actions.
- esc is usually processed via KeyDown: KeyPress doesn t fire and KeyUp behaves differently for
input
s and textarea
s in different browsers (mostly due to loss of focus)
- If you d like to adjust height of a text area to the content, you probably won t use onKeyDown but rather onKeyPress (PS ok, it s actually better to use onChange for this case).
我在我的项目中使用了所有3个,但不幸可能忘记了一些务实的做法。 (待指出:还有<条码>输入条码>和<条码>变动条码>事项>。)