keypress和keyup - 为什么keyCode不同? [英] keypress and keyup - why is the keyCode different?

查看:247
本文介绍了keypress和keyup - 为什么keyCode不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关: JavaScript KeyCode vs CharCode



以下是您可以在家中或 jsfiddle

  el.addEventListener('keyup',function(e){
console.log('Keyup event ');
console.log(e.keyCode);
});
el.addEventListener('keypress',function(e){
console.log('Keypress event');
console.log(e.keyCode);
}) ;

为什么keyCode不同?



我可以理解为什么只应该使用按键,但我不明白的是,在键盘上给出相同的按键时,两个按键事件如何给出不同的keyCodes。



PS:我并不担心遗留浏览器的支持,我在Chrome中尝试了这个并且感到很惊讶,并且无法找到解释。

解决方案

这些事件的目的完全不同。使用 keyup keydown 来识别物理键和 keypress 识别键入的字符。这两者是根本不同的任务,具有不同的事件;不要试图混合两者。特别是 keypress 上的 keypress 事件通常是多余的,不应该使用(旧的IE除外,但请参阅下面的链接文件了解更多信息);对于可打印的按键,它通常与相同, charCode ,尽管浏览器之间存在一些差异。



Jan Wolter关于重要事件的文章,已经链接到在另一个答案中,对我来说是关于这个主题的权威性词汇,并且有表格描述每种类型的关键事件和每个浏览器返回的每个不同属性。


Related: JavaScript KeyCode vs CharCode

Here is some code you can try at home or in a jsfiddle:

el.addEventListener( 'keyup', function( e ) { 
    console.log( 'Keyup event' );
    console.log( e.keyCode );
} ); 
el.addEventListener( 'keypress', function( e ) { 
    console.log( 'Keypress event' );
    console.log( e.keyCode );
} );

Why is the keyCode different?

I can understand why one should use keypress only, but what I don't understand is how two key events, given the same hit key on the keyboard, give different keyCodes.

PS: I'm not worrying about legacy browsers support, I tried this in Chrome and was surprised, and couldn't find an explanation.

解决方案

The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two. In particular, keyCode on keypress events is usually redundant and shouldn't be used (except in older IE, but see the linked document below for more on that); for printable keypresses it's usually the same as which and charCode, although there is some variation between browsers.

Jan Wolter's article on key events, already linked to in another answer, is the definitive word on this subject for me and has tables describing what each of the different properties returns for each type of key event and each browser.

这篇关于keypress和keyup - 为什么keyCode不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆