【问题标题】:detect altKey and/or ctrlKey检测 altKey 和/或 ctrlKey
【发布时间】:2015-09-23 20:58:59
【问题描述】:

下面的代码可以在 FF (Firefox) 中运行,但不能在 chrome 中运行。 Chrome 不会对 altKey 或 ctrlKey 起作用,但如果我写 e.shiftKey 它会起作用 有没有办法让 chrome 对 altkey 和 ctrlkey 起作用(并且它在 FF 中仍然有效)?

document.onkeypress = function(e) {
  if(e.altKey && e.shiftKey) {
     alert("Test");
  }
}

我找到了一个话题讨论 chrome 和 FF 在这件事上的差异,但不幸的是,这对我没有帮助:

Detect Alt Gr (Alt Graph) modifier on key press

【问题讨论】:

  • 您无法在 chrome 浏览器中检测到 alt 键,请参阅 SO 前面的 discussion

标签: javascript google-chrome firefox


【解决方案1】:

在 chrome 中的 Alt 上不会捕获 keypress 事件,但您可以改用 keydown 事件。我建议在大多数情况下使用 keydown 事件而不是 keypress,因为 Firefox 不会在 SHIFT 等修饰键上触发按键事件,并且基于 Webkit 的浏览器(例如 Google Chrome 和 Safari)不会在箭头键上触发按键事件¹ .

keydown 事件会在这些浏览器中针对这些键触发,并且应该更可靠。

¹取自here

【讨论】:

    猜你喜欢
    • 2014-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2017-07-01
    • 2011-06-20
    • 1970-01-01
    相关资源
    最近更新 更多