为什么我可以在 keydown 上阻止 Default 事件,但在使用 Javascript 的 keyup 上却不能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19689475/
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-10-27 16:29:29  来源:igfitidea点击:

Why can I preventDefault event on keydown but not on keyup with Javascript?

javascriptjquery

提问by Aaron

When using .keydownI can capture keydown event, then check and prevent default action (display the character).

使用时.keydown我可以捕获 keydown 事件,然后检查并阻止默认操作(显示字符)。

When using .keyupI cannot?

使用时.keyup我不能?

I know the event is being captured as alert()fires when the code is inside the condition yet the preventDefault()doesn't prevent the action.

我知道alert()当代码在条件内但preventDefault()不会阻止操作时,事件被捕获为火。

Here is a full DEMO

这是一个完整的演示

回答by frogatto

In keyupevent the character has been typed and can't be undone but in keydownnothing has been typed and the browser has intentto type the character, so you can cancel the browser intent.

keyup事件中的角色已被键入,不能撤消,但keydown什么也没有输入和浏览器有意向键入字符,这样你就可以取消浏览器的意图。

Whenever you type a character the following events occur:

每当您键入一个字符时,就会发生以下事件:

keydown--> keypressrepeatedly until the key is released --> keyup

keydown-->keypress重复直到按键被释放 -->keyup

  • keydown-> can be prevented -> fired when pressa key
  • keypress-> can be prevented -> fired when holda key
  • keyup-> cannot be prevented -> fired when releasea key
  • keydown-> 可以防止 ->按下按键时触发
  • keypress-> 可以防止 ->按住键时触发
  • keyup-> 无法阻止 ->释放按键时触发

回答by SidOfc

the keydown()event is fired when the key is hit, meaning that code can be executed before the key is released.

keydown()事件在击键时触发,这意味着可以在释放键之前执行代码。

When the key is pressed code can prevent an action, because it simply hasn't happened yet, whereas on the keyup()event, it already has.

当按键被按下时,代码可以阻止一个动作,因为它还没有发生,而在keyup()事件中,它已经发生了。

e.g. a character has already been inserted into an input field when triggering keyup()

例如,触发时已将字符插入到输入字段中 keyup()

in general, keydown and keyup produce the same keycodes (when used with a given event) however keypress gives you the physical key pressed (ASCII code returned rather than keyCode)

通常,keydown 和 keyup 产生相同的键码(当与给定的事件一起使用时)但是 keypress 会为您提供按下的物理键(返回的 ASCII 代码而不是 keyCode)