【问题标题】:How to set focus on next input when the button "Enter" is pressed? (javascript)按下“Enter”按钮时如何将焦点设置在下一个输入上? (javascript)
【发布时间】:2019-12-20 11:03:53
【问题描述】:

我需要一些建议。

我创建了一个函数,当按下空格键时,它将创建一个新的输入字段。 我想知道的是如何在按下空格键时创建的输入字段上设置焦点。

提前致谢。

这是我的代码:(包括 HTML)

<div id="paper">
  <div id="content">
  <input type="text" class="input1">
  </div>
  </div>

Javascript:

'use strict';

const input1 = document.querySelector('.input1');
const add = input1.addEventListener('keydown', function(e){
        if((e.keyCode === 13)){
        return mover();
        }
      });

 const mover = function(){
  const mega = document.createElement('input');
  const content = document.getElementById('content');
  content.appendChild(mega);
  mega.style.border = "0px solid";
  mega.style.marginTop = "75px";
  mega.style.width = "600px";
}

【问题讨论】:

    标签: javascript input focus createelement


    【解决方案1】:

    这样的东西,可以解决问题。

    const container = document.getElementById("inputs-container");
    let inputs = document.getElementsByTagName("input");
    
    // Add input on press Enter
    document.onkeyup = (evt) => {
      if (evt.keyCode == 32) {
        let input = document.createElement("input");
        input.type = "text";
        input.placeholder = "Input...";
        input.onkeyup = inputOnEnter;
        container.appendChild(input);
        inputs = document.getElementsByTagName("input");
      }
    };
    
    // Focus next input on Space
    const inputOnEnter = (evt) => {
      if (evt.keyCode == 13) {      
        let index = Object.keys(inputs).filter(a => inputs[a] === evt.target);
        let nextIndex = parseInt(index) + 1;
    
        if (inputs[nextIndex]) inputs[nextIndex].focus();
      }
    };
    
    for (let i = 0; i < inputs.length;i++) {
      inputs[i].onkeyup = inputOnEnter;
    }
    <div id="inputs-container">
      <input type="text" placeholder="Input..." />
    </div>

    【讨论】:

    • 我输入了您的建议,但没有成功。我复制了它,但它仍然没有工作。您建议我的代码太复杂了,因为我是初学者 javascript。我不知道为什么代码不起作用。也许你遗漏了什么?
    • 当你点击 Run Code sn-p 时它是否按预期工作?
    • 其实我只是查了一下'32'键,它是空格键。但即便如此,它也不关注创建的输入
    • 我看到了问题,都是我的错。我不小心输入了“空格键”而不是在论坛的描述中输入。您的代码运行良好,谢谢。
    • @dcnx1 好消息!不要犹豫,验证/支持我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多