jQuery .keypress & .keydown .which

对着背影说爱祢 提交于 2019-11-29 23:41:04
RvdK

If you press a button it fires a keydown and releasing it fires a keyup. The keypress usually comes between those two.

keydown and keyup talk about which key has been changed. keypress tells which character that key represents.

Note that this is all browser-dependent!

See this article about the differences between the key events as implemented on various browsers.

SpYk3HH

I'll be d$%^@d, there really is a difference with keypress and all this time I never realized. lol

See my fiddle and try something like the letter "r"

http://jsfiddle.net/SpYk3/NePCm/

Somehow I never paid attention to this

Found more info:

http://www.quirksmode.org/js/keys.html

"The two properties are keyCode and charCode. Put (too) simply, keyCode says something about the actual keyboard key the user pressed, while charCode gives the ASCII value of the resulting character. These bits of information need not be the same; for instance, a lower case 'a' and an upper case 'A' have the same keyCode, because the user presses the same key, but a different charCode because the resulting character is different.

Explorer and Opera do not support charCode. However, they give the character information in keyCode, but only with onkeypress. onkeydown and -up keyCode contains key information."

jbl

You should read the following post : http://javascript.info/tutorial/keyboard-events

Keydown triggers on any key press and gives scan-code. Keypress triggers after keydown and gives char-code, but it is guaranteed for character keys only.

In normal cases, go for keyup:

$(document).keyup(function(e){
  console.log(e.which);
});

Reasons:

  1. keydown keeps firing when user holds the keys down, while keypress and keyup fire only once.
  2. keypress doesn't detect special keys (e.g. SHIFT), keydown and keyup do.

KeyPress happens after KeyDown. So you can use KeyDown to determine what key it is, then KeyPress to disallow that character.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!