【问题标题】:How to set default input for input keypress?如何设置输入按键的默认输入?
【发布时间】:2021-01-09 11:32:06
【问题描述】:

我有一个用 React 编写的网页(但它不应该与那个问题严格相关),它由几个输入组成,我们称它们为 Name、Surname 和 Code。

为了快速工作,代码的插入是通过用作外部键盘的条码扫描仪完成的。我的想法是,如果某个字段被聚焦,则按键被插入到聚焦输入中,但是,如果没有输入聚焦,我想自动聚焦并填充代码输入。

有没有办法轻松搞定?

【问题讨论】:

  • 您想强制手动聚焦输入吗?喜欢使用参考?

标签: javascript html reactjs input


【解决方案1】:

let inputName = document.querySelector('input[name="name"]');
let inputSurname = document.querySelector('input[name="surname"]');
let inputCode = document.querySelector('input[name="code"]');

let focusedInput = null;

[inputName, inputSurname, inputCode].forEach((input) => {
  input.addEventListener('blur', () => {
    focusedInput = null;
  });
  input.addEventListener('focus', () => {
    focusedInput = input;
  });
});

document.body.addEventListener('keypress', () => {
  if (focusedInput == null) {
    inputCode.focus();
  }
});
<div>
  <label>Name</label>
  <input type="text" name="name" />
</div>
<div>
  <label>Surname</label>
  <input type="text" name="surname" />
</div>
<div>
  <label>Code</label>
  <input type="text" name="code" />
</div>

【讨论】:

    【解决方案2】:
    const surnameInput = document.getElementById('surname-input');
    ... (= do for all inputs)
    
    let activeInput;
    
    surnameInput.onFocus = () => { activeInput = surnameInput };
    ...
    
    surnameInput.OnBlur = () => { activeInput = undefined };
    ...
    
    document.addEventListener('keypress', (ev) => {
        const input = activeInput ?? codeInput;
        input.value += valueOftheKey;
    }
    

    您显然必须评估所按下的键是否具有可以添加到输入中的值,但我认为这应该让您知道该怎么做。不过我还没有尝试过,所以它可能无法完全工作。

    另外:我不确定这是否是最有效的方法,但它是一种选择。

    编辑:Kostas 的回答更好;)除了null...你应该使用undefined

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多