gpt4 book ai didi

javascript - 当没有文本输入聚焦时检测空格键按下

转载 作者:行者123 更新时间:2023-11-28 13:16:43 26 4
gpt4 key购买 nike

我想使用 JavaScript 来检测何时按下空格键。我想排除任何输入集中的所有事件。这可以用纯 JS 实现吗?

注意:这个问题的要点是排除输入聚焦的所有事件。

最佳答案

// capture keyboard input
document.onkeypress = function (e) {

// check for spacebar press
if (e.keyCode == 32) {

// check if an input is currently in focus
if (document.activeElement.nodeName.toLowerCase() != "input") {

// prevent default spacebar event (scrolling to bottom)
e.preventDefault();

// do stuff you want ...
}
}
};

观察空格键焦点的其他一些元素:

  • 文本区域
  • 按钮

关于javascript - 当没有文本输入聚焦时检测空格键按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37284120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com