keypress和keydown事件及keyCode和keyChar

二:keypress和keydown事件:

现只在IE10、chrome(版本 32.0.1700.107 m)、firefox(25.0.1)中测试了。 

 IE8chromefirefox
$(document).keydown()yesyesyes
$('window').keydown()noyesyes
$('body').keydown()noyesyes

keypress的表现与上表一致。
不仅keypress和keydown得到的按键值不同,不同浏览器的返回值event.keyCode、event.charCode也不同:

  Q键q键Caps Lock键Tab键左方向键数字1键Enter键空格键F5键
key
down
key
press
key
down
key
press
key
down
key
press
key
down
key
press
key
down
key
press
key
down
key
press
key
down
key
press
key
down
key
press
key
down
key
press
IE10keyCode81818111320--9--37--494913133232116--
charCode 081  0113  -- 0--  0 -- 0 49 0 13  32 0-- 
chromekeyCode81818111320--9937--49491313--32116--
charCode81  113 0--  0 9--  0--  13 -- 32 -- 
firefoxkeyCode81081020--993737   49 01313320116116
charCode 081  113--  0 0 049  0 032  0 0

(还有一个event.whice:A non-standard property, the hybrid of charCode and keyCode, with the sole purpose to confuse a developer.
But in the zoo of key events it also plays a good role. Particulary, it helps to get the character. )

还有一些属性:shiftKey, ctrlKey, altKey, metaKey,布尔类型的值,检测按键是否是shift、ctrl、alt、Command(Mac only).

可以看出对于keyCode:

keydown几乎对所有按键都有返回值,且对大小写字母的返回值相同;

kepress似乎对只对字母按键有返回值,且对大小写字母的返回值不一样.

关于keydown、keypress、keyup的区别,参考http://javascript.info/tutorial/keyboard-events,上面写的很详细,摘录如下:

对于keydown,任何按键事件都能触发它,并返回scan-code(按键本身固有的数字代码,所有同一个键的scan-code肯定相同);

对于keypress,只保证character keys(字符按键)事件能触发它,并返回char-code(按键的unicode字符,区分大小写按键,charCode只在keypress中返回。js中的str.charCodeAt() 方法就可返回指定位置的字符的 Unicode 编码)。

For all keys except ';', '=' and '-' different browsers use same key code.。 

 看了上面的表是不是觉得有点......,参考网页中还给出了keypress的事件代码

如何获取键入的字符值和数字值:

// only keypress event
function getChar(event) {
  if (event.which == null) {
    return String.fromCharCode(event.keyCode) // IE
  } else if (event.which!=0 && event.charCode!=0) {
    return String.fromCharCode(event.which) // the rest
  } else {
    return null // special key
  }
}

测试IE10、chrome、firefox有效。

由于String.fromCharCode对special keys 会返回weird results.所有不能直接return String.fromCharCode(event.keyCode||event.charCode)。

如何获取包含特殊键在内的组合键:

以ctrl+e为例:

document.onkeydown = function(e) {
  e = e || event;
  if ((e.ctrlKey && e.keyCode == 'E'.charCodeAt(0)) ) {
   //do something
}

由于keyCode对大小写字符返回的都是大写字母值,所以e.keyCode == 'E'.charCodeAt(0)对e和E都能识别。

测试IE10、chrome、firefox有效。(如果先按住E,再同时按ctrl,则都无效)

转载于:https://www.cnblogs.com/yigeqi/p/3554532.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值