JavaScript: keyCode应该换成什么?

JavaScript: What should keyCode be replaced with?

这是js代码:

document.addEventListener('keyup', function (e) {
    e.preventDefault();
    if (e.keyCode === 191) {
        document.getElementById('search-input').focus()
    }
})

但在 visual studio 代码中说:keyCode 已弃用。 这段代码应该替换成什么?有必要这样做吗?

将其替换为 e.key === 'Enter' 例如或 e.code === 'Enter'。 您可以找到有关它的更多信息 here and here

使用e.key。它更易于使用,并且在 每个 浏览器中工作:

document.addEventListener('keyup', function (e) {
    e.preventDefault();
    if (e.key == '/') {
        document.getElementById('search-input').focus()
    }
});

MDN 文档说明如下:

You should avoid using this (keyCode) if possible; it's been deprecated for some time. Instead, you should use KeyboardEvent.code, if it's implemented. Unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers.

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

如果您需要支持旧版浏览器(如 Internet Explorer),您可能需要使用功能检测来使用正确的浏览器。

if (event.code !== undefined) {
    // Handle the event with KeyboardEvent.key
}
else if (event.keyCode !== undefined) {
    // Handle the event with KeyboardEvent.keyCode
}