【问题标题】:How can i check if a combination of keys pressed in JavaScript [closed]我如何检查是否在 JavaScript 中按下了组合键 [关闭]
【发布时间】:2020-03-22 05:37:54
【问题描述】:

我正在编写一个程序,我想在其中添加自定义热键并存储它们。该组合必须由用户输入。假设用户选择 CTRL + M。如何存储此组合并在 Vanilla JS 中按下此组合时发出警报消息。

【问题讨论】:

标签: javascript html


【解决方案1】:

您可以使用keydown 事件来检测键盘事件,也可以在事件处理程序中使用event.ctrlKey 检查 Ctrl 键。

更新我添加了单选按钮来展示如何使用 keydown 事件动态使用组合,您还可以将其存储在数据库中并在前端显示如下:

document.addEventListener('keydown', logKey);

function logKey(e) {
  let command = document.querySelector('input[name="command"]:checked').value;
  let keypressed = document.querySelector('input[name="keypressed"]:checked').value;
  if (e.keyCode == keypressed && e[command]) alert(` ${command} + ${String.fromCharCode(e.keyCode)} pressed`);
  e.preventDefault();
  return false;
}
<label><input type="radio" name="command" value="shiftKey" checked /> Shift<label><br />
<label><input type="radio" name="command" value="ctrlKey" /> Ctrl<label><br />

<label><input type="radio" name="command" value="altKey" /> Alt<label>

<hr />

<label><input type="radio" name="keypressed" value="77" checked /> M<label><br />
<label><input type="radio" name="keypressed" value="68" /> D<label><br />
<label><input type="radio" name="keypressed" value="83" /> S<label>


<p>Focus the IFrame first (e.g. by clicking in it), then try pressing selected keys.</p>
<p id="log"></p>

【讨论】:

  • 谢谢...但这适用于 ctrlKey,是的..但是我想要一些我们可以选择组合的东西...例如 Shift + F、Ctrl + J 或任何其他 2 个组合键..可以存储在变量中,然后检查 keydown 事件...但我不知道如何将 ctrlKey 存储为变量
  • 好的,我会更新我的答案,您应该将其添加到您的问题中,因为不清楚您是否希望按照您的要求进行此操作。
  • 你能不能也添加一些东西,这样这个组合会覆盖默认热键...例如...如果我使用 CTRL + S,它应该覆盖 Chrome 的“SAVE”热键
  • @VishruthSubramanian,我添加了代码,还请注意,我添加了 e.preventDefault()return false, 以停止默认行为。
猜你喜欢
  • 1970-01-01
  • 2015-04-22
  • 2014-10-12
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多