javascript - addEventListener 未在旧 Chrome 版本中正确处理键
问题描述
我正在尝试通过这样的用户脚本向网站添加事件侦听器:
// ==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, k, 。l or n
这里可能是什么问题?谢谢。
(我目前仅限于旧的 OSX,所以 Firefox 和 Chrome 都很旧——Chrome 已经 49 岁了——但我怀疑这应该是一个问题......)
解决方案
该.key
属性在 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...
推荐阅读
- sql - SQL Server 中视图(查看的表)生成显着延迟
- flutter - 当网页(由 Flutter for Web 创建)向上或向下滚动时,嵌入式 Youtube 视频小部件消失
- node.js - 错误:Dialogflow 中的 getaddrinfo EAI_AGAIN myWebsiteName.com:443
- javascript - Test.js 没有通过破坏性的 ES6 程序
- c++ - '错误 C0000: 语法错误,意外 $end at token "
"' 并且不确定如何进行 - python - Pandas:聚合后每个组的计数器列
- mongodb - 使用 mongo-spark-connector 连接到 mongodb 时出错
- react-native - 如何在卡片上方显示组件图像
- bash - 将所有输出重定向到 lolcat
- javascript - css 溢出:隐藏导致鼠标 layerX & layerY 位置不正确