keypress 和 keyup - 为什么 keyCode 不同?

keypress and keyup - why is the keyCode different?(keypress 和 keyup - 为什么 keyCode 不同?)
本文介绍了keypress 和 keyup - 为什么 keyCode 不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

相关:JavaScript KeyCode vs CharCode

这里有一些代码,您可以在家中或在 jsfiddle 中尝试:

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 );
} );

为什么keyCode不一样?

Why is the keyCode different?

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

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:我不担心旧版浏览器的支持,我在 Chrome 中尝试过,很惊讶,但找不到解释.

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

推荐答案

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

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 关于关键事件的文章,已经在另一个答案中链接到,是权威词对我来说这个主题,并有表格描述了每种不同属性为每种类型的键事件和每种浏览器返回的内容.

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 不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)