输入时如何禁用热键? [英] How to disable hotkeys when inputting?

查看:114
本文介绍了输入时如何禁用热键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户按下某个键时,将显示一个组件.我有四个这样的组成部分.用户输入或编辑时,我想禁用热键.

When the user presses a certain key, a component shows. I have four such components. When the user is typing or editing, I want to disable the hotkeys.

我在四个组件的每一个中都有此代码

I have this code in each of the four components

componentDidMount(){
    document.body.addEventListener("keypress", (e) => {
        if (e.key === "t") { // "n" "w" "," for the others
            this.setState({opened: !this.state.opened});
        }
    });
}

我只想在用户键入或编辑时禁用热键.有没有办法知道是否有任何关注的焦点?或以其他方式,仅当所有输入均处于模糊"状态时,我们才能添加事件侦听器吗?

I only want to disable hotkeys when the user is typing or editing. Is there a way to know if any input is in focus? Or the other way, can we add the event listeners only if all the inputs are 'on blur'?

推荐答案

因此,我们需要知道页面上的任何输入是否在焦点上,并且如果其中任何一个都在焦点上,那么我们只是不做任何显示或隐藏组件.

So we need to know if any of the inputs on the page are in focus and if any of them is focused then we just will not do anything to show or hide components.

让我们假设我们的组件处于状态状态,该属性指示页面上的某些输入已聚焦,我们将其称为isFocus.

Let's assume that our component has in the state some property which indicates that some input on the page is focused, let's call it isFocus.

因此,我们需要收集页面上的所有输入,遍历所有输入并将focusblur事件处理程序分配给每个输入,因此我们将能够知道何时更改isFocus财产.

So, we need to collect all inputs on the page, iterate over them all and assign to each input the focus and the blur event handlers, so we will be able to know when to change the isFocus property in the state.

首先,我们需要收集页面上的所有输入,我们可以这样做:

First of all, we need to collect all of the inputs on the page, we do it with:

const inputs = document.getElementsByTagName('input').

遍历所有对象并分配focusblur事件处理程序:

Iterate over them all and assign the focus and blur event handlers:

for (let input of inputs) {
    input.addEventListener('focus', () => this.setState({isFocus: true}));
    input.addEventListener('blur', () => this.setState({isFocus: false}));
}

最后,让我们更改keypress事件的条件:

And finally, let's change the condition for the keypress event:

document.addEventListener('keypress', e => {
    if (!this.state.isFocus && e.key === "t") {
        this.setState({opened: !this.state.opened});
    }
});

一切都将如下所示:

componentDidMount() {
    const inputs = document.getElementsByTagName('input');
    for (let input of inputs) {
        input.addEventListener('focus', () => this.setState({isFocus: true}));
        input.addEventListener('blur', () => this.setState({isFocus: false}));
    }

    document.addEventListener('keypress', e => {
        if (!this.state.isFocus && e.key === "t") {
            this.setState({opened: !this.state.opened});
        }
    });
  }

希望这会有所帮助.祝你好运.

Hope this helps. Good luck.

这篇关于输入时如何禁用热键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆