【问题标题】:addEventListener not handling keys right in old Chrome versionaddEventListener 未在旧 Chrome 版本中正确处理键
【发布时间】:2018-08-29 07:38:52
【问题描述】:

我正在尝试通过这样的用户脚本向网站添加事件侦听器:

// ==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 中,出于某种原因,我得到的始终是“否”,无论是 Spacej例如,按 kbd>、kl n

这可能是什么问题?谢谢。

(目前我仅限于使用旧的 OSX,因此 Firefox 和 Chrome 都很旧——Chrome 已经 49 岁了——但我怀疑这应该是一个问题......)

【问题讨论】:

    标签: javascript google-chrome addeventlistener event-listener userscripts


    【解决方案1】:

    .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...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 2020-06-06
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      相关资源
      最近更新 更多