问题描述
在事件监听器中,我使用的是 e.key
,但似乎许多旧版浏览器均不支持它。
In a event listener I am using e.key
, but it seems it is not supported by many older browsers.
来自和我可以看到 e.keyCode
和 e。其中
已弃用,而推荐使用 e.key
,因此我想使用 e.key
,但是某些浏览器不支持它怎么办?
From https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode and https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which I can read that e.keyCode
and e.which
are deprecated in favor of e.key
, so I want to use e.key
, but what should I do when some browsers are not supporting it?
我应该使用
const key = e.key || String.fromCharCode(e.keyCode);
例如,如果关键是,它们似乎不会给我相同的结果,
It just seems that they don't give me the same results if the key is, for instance, a comma.
推荐答案
您可以使用所有受支持的方法,首先从首选的 e开始进行检查。键
,所有浏览器都会及时支持
You use whichever is supported by checking them all, starting with the preferred e.key
which will be supported by all browsers in time
if (e.key) {
var key = e.key;
} else {
var code = e.which || e.keyCode;
var key = String.fromCharCode(code);
}
他们应该返回相同字符
document.getElementById('test').addEventListener('keypress', function(e) {
var code = e.which || e.keyCode;
var key = String.fromCharCode(code);
console.log(key, e.key)
});
<p>Type in the input !</p>
<input id="test">
请注意,快捷键
和 keydown
事件将为某些键返回不同的键码。
Note that keyup
and keydown
events will return different keycodes for certain keys.
这篇关于大多数浏览器不支持e.key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!