javascript - How to set focus on next input when the button "Enter" is pressed? (javascript)
问题描述
I need some advice.
I have created a function where when spacebar is pressed, it'll create a new input field. What i would like to know is how to set focus on the input field that has been created when spacebar is pressed.
Thanks in advance.
Here is my code: (HTML included)
<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";
}
解决方案
像这样的东西,可以做的伎俩。
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>
推荐阅读
- c# - 如何在 Word 文档中“标记”一段文本,以便使用 Interop.Word 轻松删除它
- css - 如何将@font-face 用于 Manrope 字体?
- javascript - 如何获得可重用的菜单组件?
- android - Android 单元测试 ViewModel 需要但未调用
- python-3.x - 让 OpenCV 的“不失真”更有效地运行的简单方法?
- python - 在 Pandas 中创建一个新列
- javascript - 苗条打字稿上的苗条自定义事件
- java - WSO2 - 将 java 类作为项目的一部分包含的正确方法是什么
- javascript - 如何从 list.stdout.on 方法中获取数据
- webhooks - Podio Webhooks 响应未出现在 webhook.site 中