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

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

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)