Javascript onKeyPress 对比 onKeyUp 和 onKeyDown

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3396754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:28:09  来源:igfitidea点击:

onKeyPress Vs. onKeyUp and onKeyDown

javascriptdomdom-events

提问by instantsetsuna

What is the difference between these three events? Upon googling I found that:

这三个事件有什么区别?谷歌搜索后,我发现:

  • The onKeyDownevent is triggered when the user presses a key.
  • The onKeyUpevent is triggered when the user releases a key.
  • The onKeyPressevent is triggered when the user presses & releases a key (onKeyDownfollowed by onKeyUp).
  • onKeyDown当用户按下某个键时触发该事件。
  • onKeyUp当用户松开按键时触发该事件。
  • onKeyPress当用户按下并释放某个键(onKeyDown后跟onKeyUp)时触发该事件。

I understand the first two, but isn't onKeyPressthe same as onKeyUp? Is it possible to release a key (onKeyUp) without pressing it (onKeyDown)?

我理解前两个,但不onKeyPress一样onKeyUp吗?是否可以在onKeyUp不按下( ) 的情况下释放键( onKeyDown)?

This is a bit confusing, can someone clear this up for me?

这有点令人困惑,有人可以帮我解决这个问题吗?

采纳答案by dcp

Check here for the archived linkoriginally used in this answer.

在此处查看此答案中最初使用的存档链接

From that link:

从该链接:

In theory, the onKeyDownand onKeyUpevents represent keys being pressed or released, while the onKeyPressevent represents a character being typed. The implementation of the theory is not same in all browsers.

理论上,onKeyDownonKeyUp事件代表按键被按下或释放,而onKeyPress事件代表正在输入的字符。该理论的实现在所有浏览器中并不相同。

回答by Robusto

KeyPress, KeyUpand KeyDownare analogous to, respectively: Click, MouseUp,and MouseDown.

KeyPressKeyUpKeyDown分别类似于:ClickMouseUp,MouseDown

  1. Downhappens first
  2. Presshappens second (when text is entered)
  3. Uphappens last (when text input is complete).
  1. Down先发生
  2. Press第二次发生(输入文本时)
  3. Up最后发生(当文本输入完成时)。

The exception is webkit, which has an extra event in there:

例外是webkit,它有一个额外的事件:

keydown
keypress
textInput     
keyup

Below is a snippet you can use to see for yourself when the events get fired:

以下是您可以在事件触发时自己查看的片段:

window.addEventListener("keyup", log);
window.addEventListener("keypress", log);
window.addEventListener("keydown", log);

function log(event){
  console.log( event.type );
}

回答by Nick

Most of the answers here are focused more on theory than practical matters and there's some big differences between keyupand keypressas it pertains to input field values, at least in Firefox (tested in 43).

大部分的答案在这里更侧重于理论而不是实际的问题,并有存在着很大的差异keyup,并keypress因为它涉及到输入字段值,至少在Firefox(43测试)。

If the user types 1into an empty input element:

如果用户1输入一个空的 input 元素:

  1. The value of the input element will be an empty string (old value) inside the keypresshandler

  2. The value of the input element will be 1(new value) inside the keyuphandler.

  1. 输入元素的值将是keypress处理程序内的空字符串(旧值)

  2. 输入元素的值将是处理程序1内的(新值)keyup

This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.

如果您正在做一些依赖于知道输入后的新值而不是当前值(例如内联验证或自动制表符)的操作,这一点至关重要。

Scenario:

设想:

  1. The user types 12345into an input element.
  2. The user selects the text 12345.
  3. The user types the letter A.
  1. 用户键入12345输入元素。
  2. 用户选择文本12345
  3. 用户键入字母A

When the keypressevent fires after entering the letter A, the text box now contains only the letter A.

keypress输入字母后事件触发时A,文本框现在只包含字母A

But:

但:

  1. Field.val() is 12345.
  2. $Field.val().length is 5
  3. The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).
  1. Field.val() 是12345.
  2. $Field.val().length 是 5
  3. 用户选择是一个空字符串(防止您确定通过覆盖选择删除了什么)。

So it seems that the browser (Firefox 43) erases the user's selection, thenfires the keypressevent, thenupdates the fields contents, thenfires keyup.

因此,浏览器(Firefox 43)似乎会删除用户的选择,然后触发keypress事件,然后更新字段内容,然后触发keyup.

回答by arunjitsingh

onkeydownis fired when the key is down (like in shortcuts; for example, in Ctrl+A, Ctrlis held 'down'.

onkeydown当键按下时触发(就像在快捷键中一样;例如, in Ctrl+ACtrl被按住“按下”。

onkeyupis fired when the key is released (including modifier/etc keys)

onkeyup释放键时触发(包括修饰符/等键)

onkeypressis fired as a combination of onkeydownand onkeyup, or depending on keyboard repeat (when onkeyupisn't fired). (this repeat behaviour is something that I haven't tested. If you do test, add a comment!)

onkeypress被烧制的组合onkeydownonkeyup,或根据键盘重复(当onkeyup不触发)。(这种重复行为是我没有测试过的。如果你做了测试,请添加评论!)

textInput(webkit only) is fired when some text is entered (for example, Shift+Awould enter uppercase 'A', but Ctrl+Awould select text and not enter any text input. In that case, all other events are fired)

textInput(仅限 webkit)在输入某些文本时触发(例如,Shift+A输入大写的“A”,但Ctrl+A会选择文本而不输入任何文本输入。在这种情况下,将触发所有其他事件)

回答by YakovL

First, they have different meaning: they fire:

首先,它们有不同的含义:它们开火:

  • KeyDown – when a key was pushed down
  • KeyUp – when a pushed button was released, and afterthe 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).
  • KeyDown – 当一个键被按下时
  • KeyUp – 当一个按钮被释放时,并且input/textarea 的值被更新后(其中唯一的一个)
  • KeyPress – 在这些和之间实际上并不意味着按下和释放一个键(见下文)。

Second, some keys fire some of these events and don't fire others. For instance,

其次,某些键会触发其中一些事件,而不会触发其他事件。例如,

  • KeyPress ignores delete, arrows, PgUp/PgDn, home/end, ctrl, alt, shiftetc while KeyDown and KeyUp don't (see details about escbelow);
  • when you switch window via alt+tabin Windows, only KeyDown for altfires because window switching happens before any other event (and KeyDown for tabis prevented by system, I suppose, at least in Chrome 71).
  • 按键响应忽略delete,箭头,PgUp/ PgDnhome/ endctrlaltshift等等而KeyDown和KEYUP不(见关于细节esc下文);
  • 当您在 Windows 中通过alt+切换窗口时tab,只有 KeyDown foralt触发,因为窗口切换发生在任何其他事件之前(并且 KeyDown fortab被系统阻止,我想,至少在 Chrome 71 中)。

Also, you should keep in mind that event.keyCode(and event.which) usually have same value for KeyDown and KeyUp but different one for KeyPress. Try the playgroundI've created. By the way, I've noticed quite a quirk: in Chrome, when I press ctrl+aand the input/textareais empty, for KeyPress fires with event.keyCode(and event.which) equal to 1! (when the input is not empty, it doesn't fire at all).

此外,您应该记住,event.keyCode(和event.which)通常对于 KeyDown 和 KeyUp 具有相同的值,但对于 KeyPress 具有不同的值。试试我创建的游乐场。顺便说一句,我注意到了一个奇怪的地方:在 Chrome 中,当我按下ctrl+a并且input/textarea为空时,对于 KeyPress 以event.keyCode(和event.which) 等于1! (当输入不为空时,它根本不会触发)。

Finally, there's some 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.
  • escis usually processed via KeyDown: KeyPress doesn't fire and KeyUp behaves differently for inputs and textareas 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).
  • 对于处理箭头,您可能需要使用 onKeyDown:如果用户按住 ,则 KeyDown 会触发多次(而 KeyUp 在释放按钮时仅触发一次)。此外,在某些情况下,您可以轻松阻止 KeyDown 的传播,但不能(或不能那么容易)阻止 KeyUp 的传播(例如,如果您想在不向文本字段添加换行符的情况下在输入时提交)。
  • 令人惊讶的是,当你按住一个键时,比如在 中textarea,KeyPress 和 KeyDown 都会触发多次(Chrome 71),如果我需要多次触发的事件和 KeyUp 用于单键释放,我会使用 KeyDown。
  • 当您必须对游戏的操作提供更好的响应时,KeyDown 通常更适合游戏。
  • esc通常通过 KeyDown 处理:KeyPress 不会触发,并且 KeyUp在不同浏览器中对inputs 和textareas 的行为不同(主要是由于失去焦点)
  • 如果您想根据内容调整文本区域的高度,您可能不会使用 onKeyDown 而是使用 onKeyPress (PS 好的,实际上在这种情况下使用 onChange 更好)。

I've used all 3 in my project but unfortunately may have forgotten some of pragmatics. (to be noted: there's also inputand changeevents)

我在我的项目中使用了所有 3 个,但不幸的是可能忘记了一些语用学。(要注意:还有inputchange事件)

回答by Falk

It seems that onkeypress and onkeydown do the same (whithin the small difference of shortcut keys already mentioned above).

似乎 onkeypress 和 onkeydown 做同样的事情(除了上面已经提到的快捷键的微小差异)。

You can try this:

你可以试试这个:

<textarea type="text" onkeypress="this.value=this.value + 'onkeypress '"></textarea>
<textarea type="text" onkeydown="this.value=this.value + 'onkeydown '" ></textarea>
<textarea type="text" onkeyup="this.value=this.value + 'onkeyup '" ></textarea>

And you will see that the events onkeypress and onkeydown are both triggered while the key is pressed and not when the key is pressed.

您将看到 onkeypress 和 onkeydown 事件都是在按下键时触发的,而不是在按下键时触发。

The difference is that the event is triggered not once but many times (as long as you hold the key pressed). Be aware of that and handle them accordingly.

不同之处在于事件不是一次触发而是多次触发(只要您按住键)。请注意这一点并相应地处理它们。

回答by Suraj Jain

This articleby Jan Wolter is the best piece I have came across, you can find the archived copy hereif link is dead.

Jan Wolter 的这篇文章是我遇到的最好的文章,如果链接失效,您可以在此处找到存档副本。

It explains all browser key events really well,

它很好地解释了所有浏览器关键事件,

The keydownevent occurs when the key is pressed, followed immediately by the keypress event. Then the keyupevent is generated when the key is released.

To understand the difference between keydownand keypress, it is useful to distinguish between charactersand keys. A keyis a physical button on the computer's keyboard. A characteris a symbol typed by pressing a button. On a US keyboard, hitting the 4key while holding down the Shiftkey typically produces a "dollar sign" character. This is not necessarily the case on every keyboard in the world. In theory, the keydownand keyupevents represent keys being pressed or released, while the keypressevent represents a character being typed. In practice, this is not always the way it is implemented.

For a while, some browers fired an additional event, called textInput, immediately after keypress. Early versions of the DOM 3 standard intended this as a replacement for the keypressevent, but the whole notion was later revoked. Webkit supported this between versions 525 and 533, and I'm told IE supported it, but I never detected that, possibly because Webkit required it to be called textInputwhile IE called it textinput.

There is also an event called input, supported by all browsers, which is fired just after a change is made to to a textareaor input field. Typically keypress will fire, then the typed character will appear in the text area, then input will fire. The inputevent doesn't actually give any information about what key was typed - you'd have to inspect the textbox to figure it out what changed - so we don't really consider it a key event and don't really document it here. Though it was originally defined only for textareas and input boxes, I believe there is some movement toward generalizing it to fire on other types of objects as well.

KEYDOWN事件发生时,按下该键,紧接着的按键事件。然后在松开按键时产生keyup事件。

要了解keydownkeypress之间的区别,区分字符很有用。一个关键是计算机的键盘上的物理按键。甲字符是通过按压按钮类型的符号。在美式键盘上,4按住键的同时按下Shift键通常会产生“美元符号”字符。世界上的每个键盘不一定都是这种情况。理论上,keydownkeyup事件代表按键被按下或释放,而keypress事件表示正在键入的字符。在实践中,这并不总是它的实施方式。

有一段时间,某些浏览器发射一个额外的项目,叫做为textInput后,立即按键。DOM 3 标准的早期版本打算将其作为按键事件的替代品,但整个概念后来被撤销。Webkit 在 525 和 533 版本之间支持这一点,我被告知 IE 支持它,但我从未检测到这一点,可能是因为 Webkit 要求将其称为textInput而 IE 将其称为textinput

还有一个名为input的事件,所有浏览器都支持,它会在对textarea或 input 字段进行更改后立即触发。通常按键将触发,然后键入的字符将出现在文本区域中,然后输入将触发。该输入事件实际上并不给什么键被输入的任何信息-你不得不检查文本框弄明白发生了什么变化-所以我们真的不认为这是一个关键事件,并不能真正在这里记录它. 虽然它最初只是为 textareas 和输入框定义的,但我相信有一些运动将它推广到其他类型的对象上。

回答by Mohd Sadiq

The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.

onkeypress 事件适用于所有浏览器中除 ALT、CTRL、SHIFT、ESC 之外的所有键,而 onkeydown 事件适用于所有键。表示 onkeydown 事件捕获所有键。

回答by Drummer

Just wanted to share a curiosity:

只是想分享一个好奇心:

when using the onkeydown event to activate a JS method, the charcode for that event is NOT the same as the one you get with onkeypress!

当使用 onkeydown 事件激活 JS 方法时,该事件的字符码与您使用 onkeypress 获得的字符码不同!

For instance the numpad keys will return the same charcodes as the number keys above the letter keys when using onkeypress, but NOT when using onkeydown !

例如,当使用 onkeypress 时,小键盘键将返回与字母键上方的数字键相同的字符代码,但在使用 onkeydown 时不会!

Took me quite a few seconds to figure out why my script which checked for certain charcodes failed when using onkeydown!

我花了好几秒钟才弄清楚为什么我的脚本在使用 onkeydown 时检查某些字符代码失败!

Demo: https://www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

演示:https: //www.w3schools.com/code/tryit.asp?filename=FMMBXKZLP1MK

and yes. I do know the definition of the methods are different.. but the thing that is very confusing is that in both methods the result of the event is retrieved using event.keyCode.. but they do not return the same value.. not a very declarative implementation.

是的。我确实知道方法的定义是不同的..但非常令人困惑的是,在这两种方法中,事件的结果都是使用 event.keyCode 检索的..但它们不返回相同的值..不是很声明式实现。

回答by Ken Chan

Basically, these events act differently on different browser type and version, I created a little jsBin test and you can check the console for find out how these events behavior for your targeted environment, hope this help. http://jsbin.com/zipivadu/10/edit

基本上,这些事件在不同的浏览器类型和版本上的行为不同,我创建了一个小 jsBin 测试,您可以检查控制台以了解这些事件在您的目标环境中的行为方式,希望对您有所帮助。http://jsbin.com/zipivadu/10/edit