KeyboardEvent keyCode Property

Definition and Usage

The keyCode property returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event.

The difference between the two code types:

  • Character codes - A number which represents an ASCII character
  • Key codes - A number which represents an actual key on the keyboard

These types do not always mean the same thing; for example, a lower case "w" and an upper case "W" have the same keyboard code, because the key that is pressed on the keyboard is the same (just "W" = the number "87"), but a different character code because the resulting character is different (either "w" or "W", which is "119" or "87") - See "More Examples" below to better understand it.

Tip: To find out if the user is pressing a printable key (e.g. "a" or "5"), it is recommended to use this property on the onkeypress event. To find out if the user is pressing a function key (e.g. "F1", "CAPS LOCK" or "Home") use the onkeydown or onkeyup event.

Note: In Firefox, the keyCode property does not work on the onkeypress event (will only return 0). For a cross-browser solution, use the which property together with keyCode, e.g:

which

Tip: For a list of all Unicode characters, please study our Complete Unicode Reference.

Tip: If you want to convert the returned Unicode value into a character, use the fromCharCode() method.

Note: This property is read-only.

Note: Both the keyCode and which property is provided for compatibility only. The latest version of the DOM Events Specification recommend using the key property instead (if available).

Tip: If you want to find out whether the "ALT", "CTRL", "META" or "SHIFT" key was pressed when a key event occured, use the altKeyctrlKeymetaKey or shiftKeyproperty.

 

Example

Using onkeypress and onkeydown to demonstrate the differences between character codes and keyboard codes:

<input type="text" οnkeypress="uniCharCode(event)" οnkeydοwn="uniKeyCode(event)"> 

function uniCharCode(event) {
    var char = event.which || event.keyCode;
    document.getElementById("demo").innerHTML = "Unicode CHARACTER code: " + char;
}

function uniKeyCode(event) {
    var key = event.keyCode;
    document.getElementById("demo2").innerHTML = "Unicode KEY code: " + key;
}

When pressing the "a" key on the keyboard (not using caps lock), the result of char and key will be:

Unicode CHARACTER code: 97
Unicode KEY code: 65
https://www.w3schools.com/jsref/event_key_keycode.asp请参考官方网站

转载于:https://www.cnblogs.com/woodyliang/p/7527929.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值