如何阻止我的 activeElement.value 修改修改 activeElement 和以下元素?

How do I stop my activeElement.value modifications from modifying the activeElement and the following element?

提问人:Kaelirk 提问时间:10/5/2023 最后编辑:fudoKaelirk 更新时间:10/5/2023 访问量:23

问:

我正在创建一组输入框,每个输入框接受 1 个字符。

每当我按下一个字符时,我都希望将document.activeElement.value设置为event.key的值,然后我想将()集中在下一个输入框上。

同样,每当我按下退格键或删除键时,我都希望将 activeElement 的值设置为“”,并且我应该根据需要将 () 集中在上一个或下一个输入上一个或下一个输入上。

这在某种程度上是有效的,但是在按下键时,输入被应用于 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 值的代码仍在运行,但我不确定如何在不完全更改代码的情况下停止它。有什么想法吗?

JavaScript

评论

0赞 Barmar 10/5/2023
欢迎来到 Stack Overflow!请发布一个最小的可重现示例。您可以使用堆栈代码段使其可执行。
0赞 Barmar 10/5/2023
你试过用代替吗?keyupkeydown

答:

0赞 Yosef Tukachinsky 10/5/2023 #1

您可以自己为事件和管理输入值。下面是一个工作示例: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>