我正在创建一组输入框,每个输入框接受 1 个字符。
每当我按下一个字符时,我希望将 document.activeElement.value 设置为 event.key 的值,然后我想 focus() 到下一个输入框。
类似地,每当我按退格键或删除键时,我都希望将 activeElement 的值设置为“”,并且我要根据需要对上一个或下一个输入进行 focus() 操作。
这有点工作,但是输入在按下 keydown 时应用于 activeElement 以及运行 focus() 代码后聚焦的下一个 activeElement。
以下是我迄今为止尝试过的一些片段:
在此块中,代码的目的是清除活动输入框的值并将焦点退格到前一个输入框。但相反,它会清除 activeElement 的值,将焦点退到前一个输入框,然后也清除前一个框的值。
element.addEventListener('keydown', function(event) {
if (event.key == "Backspace"){
console.log("backspaced");
if (document.activeElement.id == "1"){
console.log("cannot return any further");
}
document.activeElement.value = '';
let index = (parseInt(document.activeElement.id)) - 1;
document.getElementById(index).focus();
}
和
在此块中,代码的目的是将 event.key 的值应用于 activeElement,然后将焦点移动到下一个输入框。相反,它将 event.key 的值应用于 activeElement,将焦点移动到下一个输入框,然后更改新的 activeElement 的值。
if (event.key.length == 1 || (event.key.length > 1 && /[^a-zA-Z0-9]/.test(event.key))){
console.log("something was pressed");
if (document.activeElement.id == "9"){
console.log("password complete");
}
document.activeElement.value = event.key;
let index = (parseInt(document.activeElement.id)) + 1;
document.getElementById(index).focus();
}
我怀疑更改 activeElement 值的代码在焦点更改后仍在运行,但我不确定如何在不完全更改代码的情况下停止此操作。有什么想法吗?
您可以
preventDefault
参与事件并自行管理输入值。这是一个工作示例:
function handleInputChange(event) {
event.preventDefault();
const input = event.target;
const index = +input.id.substring(1);
if(/^[a-zA-Z0-9]$/.test(event.key)) {
input.value = event.key;
if(index < 5) document.querySelector(`#i${index+1}`).focus();
}
else if(event.code === 'Backspace') {
input.value = '';
if(index > 1) document.querySelector(`#i${index - 1}`).focus();
}
}
#container {
display: flex;
gap: 6px;
}
input {
display: block;
width: 20px;
height: 20px;
border-radius: 6px;
border: 1px solid #c1c1c1;
text-align: center;
}
<div id="container">
<input id="i1" onkeydown="handleInputChange(event)"/>
<input id="i2" onkeydown="handleInputChange(event)"/>
<input id="i3" onkeydown="handleInputChange(event)"/>
<input id="i4" onkeydown="handleInputChange(event)"/>
<input id="i5" onkeydown="handleInputChange(event)"/>
<div>