最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Why can I preventDefault event on keydown but not on keyup with Javascript? - Stack Overflow

programmeradmin0浏览0评论

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

When using .keyup I cannot?

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.

Here is a full DEMO

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

When using .keyup I cannot?

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.

Here is a full DEMO

Share Improve this question asked Oct 30, 2013 at 17:11 AaronAaron 3,2557 gold badges32 silver badges49 bronze badges 7
  • 7 keyup's action isn't to add a character to a field. That's already been and gone. – ahren Commented Oct 30, 2013 at 17:12
  • 3 Should be obvious, when the keyup event fires, the key is released and the input is already there ` – adeneo Commented Oct 30, 2013 at 17:12
  • 2 stackoverflow.com/questions/16052592/… – Arpit Commented Oct 30, 2013 at 17:14
  • You may want to trap keypress – fred02138 Commented Oct 30, 2013 at 17:14
  • Just tell yourself what happen when you keep a key dow? It does thisssssssssssssssssssssssssssssssssssss. – Karl-André Gagnon Commented Oct 30, 2013 at 17:15
 |  Show 2 more comments

2 Answers 2

Reset to default 15

In keyup event the character has been typed and can't be undone but in keydown nothing has been typed and the browser has intent to type the character, so you can cancel the browser intent.

Whenever you type a character the following events occur:

keydown --> keypress repeatedly until the key is released --> keyup

  • keydown -> can be prevented -> fired when press a key
  • keypress -> can be prevented -> fired when hold a key
  • keyup -> cannot be prevented -> fired when release a key

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

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.

e.g. a character has already been inserted into an input field when triggering 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)

发布评论

评论列表(0)

  1. 暂无评论