【问题标题】:Detect spacebar press when no text inputs are focused当没有文本输入被聚焦时检测空格键按下
【发布时间】:2016-05-17 18:51:38
【问题描述】:

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

注意:这个问题的重点是排除所有关注输入的事件。

【问题讨论】:

标签: javascript html input


【解决方案1】:
// 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 ...
        }
    }
};

注意空格键焦点的其他元素:

  • textarea
  • button

【讨论】:

  • 我知道 OP 没有提到它,但排除 textarea 可能也是个好主意。
  • ... 和<button>。可以通过按空格来激活焦点按钮。反转你的测试可能也更好——e.keyCode === 32 是一个便宜得多的测试,所以document.activeElement.nodeName.toLowerCase() != "input" 只有在命中空格时才这样做。
猜你喜欢
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
相关资源
最近更新 更多