为什么我可以在 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
Why can I preventDefault event on keydown but not on keyup with Javascript?
提问by Aaron
When using .keydown
I can capture keydown event, then check and prevent default action (display the character).
使用时.keydown
我可以捕获 keydown 事件,然后检查并阻止默认操作(显示字符)。
When using .keyup
I 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 keyup
event the character has been typed and can't be undone but in keydown
nothing 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
--> keypress
repeatedly until the key is released --> keyup
keydown
-->keypress
重复直到按键被释放 -->keyup
keydown
-> can be prevented -> fired when pressa keykeypress
-> can be prevented -> fired when holda keykeyup
-> 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)