首页 > 解决方案 > 按下键时如何专注于输入?

问题描述

所以我正在为我叔叔制作这个英亩和克拉计算器的东西,我正在使用香草 javascript,当我按下键盘上的任何小键盘键时,我想专注于文本输入并在文本框中输入该数字,我已经在网上搜索了一个小时,但我找不到我想要的。 计算器的图像

所以这就是它的样子。哦,我也忘了提到我想让点击动画在我按下键盘上的一个键时发生,但我不知道该怎么做。任何帮助将不胜感激,并提前感谢。

`

function onekey(event) {
    if(event.keyCode === 1) {
        input.focus();
        input.value += 1;
    }
 }

`

<td><button id="one" onkeypress="onekey(event)">1</button></td>

标签: javascripthtmldom

解决方案


基本上你的问题是你在听数字按钮上的按键 - 你需要创建一个全局按键监听器来监听任何按键然后更新你的输入

const input = document.getElementById('input');

function listenForKeyPress() {
  // add document event listener for all key presses
  document.addEventListener('keyup', (e) => {
    // check to see if the keypress was a number
    if (/[0-9]/g.test(e.key)) {
      // check to see if the input is not already focused
      if (document.activeElement !== input) {
        // focus element
        input.focus();
        // focus value
        input.value += e.key;
      }
    }
  })
}

// call function
listenForKeyPress();
<input id="input" type="number" />

如您所见,我们是

  1. 监听任何按键
  2. 使用正则表达式检查按键是否是 0 - 9 之间的数字
  3. 检查输入是否已经聚焦
  4. 如果输入尚未聚焦 - 聚焦输入并更新输入值

您现在可能会遇到的另一个问题是单击您的元素不会更新输入值,因此您可以执行此操作

function key(event) {
  // get input
  const input = document.getElementById('input');
  // focus input
  input.focus();
  // update the value with the innerText of the clicked element - which is the number 1
  input.value += event.toElement.innerText;
}
<input id="input" type="number" />
<button id="one" onclick="key(event)">1</button>


推荐阅读