不推荐使用KeyboardEvent.keyCode.在实践中这意味着什么? [英] KeyboardEvent.keyCode deprecated. What does this mean in practice?

查看:1697
本文介绍了不推荐使用KeyboardEvent.keyCode.在实践中这意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to MDN, we should most definitely not be using the .keyCode property. It is deprecated:

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

在W3学校中,这个事实被淡化了,只有一个旁注说明提供.keyCode仅出于兼容性考虑,而最新版本的DOM Events Specification建议使用.key属性.

On W3 school, this fact is played down and there is only a side note saying that .keyCode is provided for compatibility only and that the latest version of the DOM Events Specification recommend using the .key property instead.

问题是浏览器不支持.key,所以我们应该使用什么?有什么我想念的吗?

The problem is that .key is not supported by browsers, so what should we using? Is there something I'm missing?

推荐答案

您可以通过三种方式来处理它,因为它写在您共享的链接上.

You have three ways to handle it, as it's written on the link you shared.

if (event.key !== undefined) {

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

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

}

您应该考虑一下它们,如果要跨浏览器支持,这是正确的方法.

you should contemplate them, that's the right way if you want cross browser support.

如果实现这样的操作,可能会更容易.

It could be easier if you implement something like this.

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

这篇关于不推荐使用KeyboardEvent.keyCode.在实践中这意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆