我正在尝试通过这样的用户脚本向网站添加事件监听器:
// ==UserScript==
// @name Reuters: j/k navigation
// @version 0.01
// @match https://www.reuters.com/*
// @run-at document-start
// @grant none
// ==/UserScript==
addEventListener('keypress', e => {
if (e.ctrlKey ||
e.altKey ||
e.metaKey ||
e.shiftKey ||
(e.key !== 'k' && e.key !== 'j')) {
alert("NO");
return;
}
alert("YES");
});
虽然在 Firefox 中它确实会根据用户按下的键触发正确的警报,但在 Chrome 中出于某种原因我得到的总是“否”,无论是 Space、j例如,kbd>、k、l 或 n 被按下。
这可能是什么问题?谢谢。
(我目前仅限于使用旧的 OSX,因此 Firefox 和 Chrome 都非常旧——Chrome 是 49——但我怀疑这应该是个问题……)
最佳答案
.key
属性为 not available in Chrome 49 ;使用 .which
。
像这样:
const jKey = 'j'.charCodeAt (0);
const kKey = 'k'.charCodeAt (0);
addEventListener ('keypress', e => {
if (e.ctrlKey ||
e.altKey ||
e.metaKey ||
e.shiftKey ||
(e.which !== jKey && e.which !== kKey) ) {
console.log (e.which, "NO");
return;
}
console.log (e.which, "YES");
} );
Click here then press keys...
关于javascript - addEventListener 无法在旧版 Chrome 中正确处理键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52072024/