根据MDN,我们绝对不应该使用. keycode属性。已弃用:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

在W3学校,这个事实被淡化了,只有一个边注说。keycode只是为了兼容性而提供的,最新版本的DOM事件规范建议使用.key属性。

问题是浏览器不支持.key,那么我们应该使用什么呢?我遗漏了什么吗?


MDN已经提供了一个解决方案:

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; // Should do nothing if the default action has been cancelled
  }

  var handled = false;
  if (event.key !== undefined) {
    // Handle the event with KeyboardEvent.key and set handled true.
  } else if (event.keyIdentifier !== undefined) {
    // Handle the event with KeyboardEvent.keyIdentifier and set handled true.
  } else if (event.keyCode !== undefined) {
    // Handle the event with KeyboardEvent.keyCode and set handled true.
  }

  if (handled) {
    // Suppress "double action" if event handled
    event.preventDefault();
  }
}, true);

你有三种方法来处理它,因为它写在你分享的链接上。

if (event.key !== undefined) {

} else if (event.keyIdentifier !== undefined) {

} else if (event.keyCode !== undefined) {

}

你应该考虑它们,如果你想要跨浏览器支持,这是正确的方法。

如果你实现这样的东西,它会更容易。

var dispatchForCode = function(event, callback) {
  var code;

  if (event.key !== undefined) {
    code = event.key;
  } else if (event.keyIdentifier !== undefined) {
    code = event.keyIdentifier;
  } else if (event.keyCode !== undefined) {
    code = event.keyCode;
  }

  callback(code);
};

此外,所有的keyCode, which, charCode和keyIdentifier都已弃用: charCode和keyIdentifier是非标准特性。 keyIdentifier在Chrome 54和Opera 41.0版本被移除 在FF上正常字符的按键事件上,keyCode返回0。

键属性:

 readonly attribute DOMString key

保存与所按键对应的键属性值

在撰写本文时,所有主要浏览器都支持key属性:Firefox 52、Chrome 55、Safari 10.1、Opera 46。除了Internet Explorer 11,它有: 不标准的键标识符和错误的行为与AltGraph。更多信息 如果这很重要,或者向后兼容性很重要,那么你可以像下面的代码一样使用特性检测:

Notice that the keyvalue is different from keyCode or which properties in that : it contains the name of the key not its code. If your program needs characters' codes then you can make use of charCodeAt(). For single printable characters you can use charCodeAt(), if you're dealing with keys whose values contains multiple characters like ArrowUp chances are : you are testing for special keys and take actions accordingly. So try implementing a table of keys' values and their corresponding codes charCodeArr["ArrowUp"]=38, charCodeArr["Enter"]=13,charCodeArr[Escape]=27... and so on, please take a look at Key Values and their corresponding codes

if(e.key!=undefined){
        var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
    }else{
        /* As @Leonid suggeted   */
        var characterCode = e.which || e.charCode || e.keyCode || 0;
    }
        /* ... code making use of characterCode variable  */  

也许你想考虑向前兼容性,即使用遗留属性时,他们是可用的,只有当放弃切换到新的:

if(e.which || e.charCode || e.keyCode ){
        var characterCode = e.which || e.charCode || e.keyCode;
    }else if (e.key!=undefined){
        var characterCode = charCodeArr[e.key] || e.key.charCodeAt(0);
    }else{
        var characterCode = 0;
    }

参见:KeyboardEvent。代码属性文档和更多细节。


TLDR:我建议你使用新的事件。键和事件。代码属性而不是遗留属性。IE和Edge支持这些属性,但还不支持新的键名。对于它们,有一个小的填充,使它们输出标准的键/代码名称:

https://github.com/shvaikalesh/shim-keyboard-event-key


我在搜索与op相同的MDN警告的原因时遇到了这个问题。在搜索了更多之后,keyCode的问题变得更加清晰:

使用keyCode的问题是,非英语键盘可以产生不同的输出,甚至使用不同布局的键盘也可以产生不一致的结果。另外,还有一种情况

如果你阅读了W3C规范: https://www.w3.org/TR/uievents/#interface-keyboardevent

在实践中,keyCode和charCode在不同的平台上是不一致的,甚至在不同的操作系统上或使用不同的本地化使用相同的实现。

它深入描述了keyCode的错误: https://www.w3.org/TR/uievents/#legacy-key-attributes

这些特性从未被正式指定过,目前的浏览器实现存在很大差异。大量的遗留内容(包括脚本库)依赖于检测用户代理并据此进行操作,这意味着任何形式化这些遗留属性和事件的尝试都有可能破坏它所修复或启用的内容。此外,这些属性不适合国际使用,也不能解决可访问性问题。

因此,在确定了替换遗留keyCode的原因之后,让我们看看今天需要做什么:

All modern browsers support the new properties (key and code). IE and Edge support an older version of the spec, which has different names for some keys. You can use a shim for it: https://github.com/shvaikalesh/shim-keyboard-event-key (or roll your own - it's rather small anyways) Edge has fixed this bug in the latest release (probably will be released in Apr 2018) - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8860571/ Refer to the list of event keys you can use: https://www.w3.org/TR/uievents-key/


例如,如果你想检测“Enter”键是否被点击:

而不是

event.keyCode === 13

像这样做

event.key === 'Enter'

你可以使用

parseInt(event.key, radix: 10)

这里建议使用key value而不是keyCode,如果失败,则使用keyCode。但是这还不够,因为这个属性中的值是不兼容的。事情是new key包含控制键的字符串,比如:ArrowUp,但keyCode只包含简单的代码

String.fromCharCode(event.keyCode)

将导致不可打印的字符。下面是可打印字符的解决方案:

element.keydown((event) => {
    var symbolPressed;
    //cross browser
    if (event.key !== undefined) {
        symbolPressed = event.key; //Here control characters represented as String like: ArrowUp
        if (symbolPressed.length > 1) return; //filter out control characters
    } else if (event.keyCode !== undefined) {
        symbolPressed = String.fromCharCode(event.keyCode); //Here control chars represented as one char string
    }
    //Update this regex if you need other characters
    if (!symbolPressed.match(/[A-z0-9\s]/)) return;
    console.log(symbolPressed);
});

如果需要不可打印的控制字符,则必须相应地更新条件和正则表达式。


e.charCode已弃用:

<input
  onChange={(e) => setToken(e.target.value)}
  type="text"
  value={token}
  onKeyPress={(e) => {
    if (e.charCode === 13) {
      verifyLoginF()
    }
  }}
/>

你应该用现在:e。键=== 'Enter'


使用onkeypress和onkeydown事件。,它 是开关[字符码]或[键码]

function myKey(event){ var keycode = event.keyCode; //key code variant 1, not recomendate var keywhic = event.which; //key code variant 2, nice worked var unicode = event.key; //string name code, nice worked var chacode = event.charCode; //works onkeypress="myKey(event)" var metakey = event.metaKey; //true false, winKey or macComand document.getElementById("demo").innerHTML = keycode+" "+keywhic+" "+unicode+" "+chacode+" "+metakey; } <!DOCTYPE html> <html> <body onkeydown="myKey(event)"> <!--onkeypress="myKey(event)"--> <h1 id="demo">Keyboard Buttons click me and test the keyboard</h1> <script> //function myKey(event){ //paste code //} </script> </body> </html>