每當達到輸入框的最大長度時,我都想使用 javascript 移動到下一個輸入框。當按下退格鍵時,我想清除當前輸入框并移至上一個輸入框。
這是一種作業。除了每當我按下退格鍵時,它都會轉到上一個輸入框,但不會清除我當前所在的輸入框。
例子;
var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt){
elt.addEventListener("keydown", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13 || elt.value.length == 1) {
// Focus on the next sibling
elt.nextElementSibling.focus()
}
if( event.keyCode == 8)
{
if (elt.previousElementSibling != null)
{
elt.previousElementSibling.focus();
}
}
});
})
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1"/>
<input type="text" class="test" id="1" maxlength="1"/>
<input type="text" class="test" id="2" maxlength="1"/>
<input type="text" class="test" id="3" maxlength="1"/>
uj5u.com熱心網友回復:
嘗試
var elts = document.getElementsByClassName('test')
Array.from(elts).forEach(function(elt) {
elt.addEventListener("keydown", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13 ||
event.keyCode !== 8 && elt.value.length === Number(elt.maxLength)
) {
// Focus on the next sibling
elt.nextElementSibling.focus()
}
if (event.keyCode == 8) {
elt.value = '';
if (elt.previousElementSibling != null) {
elt.previousElementSibling.focus();
event.preventDefault();
}
}
});
})
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1" />
<input type="text" class="test" id="1" maxlength="1" />
<input type="text" class="test" id="2" maxlength="1" />
<input type="text" class="test" id="3" maxlength="1" />
uj5u.com熱心網友回復:
您是否嘗試使輸入的值等于空字串?像那樣:elt.setAttribute(value, '')
來源:
輸入元素,查找屬性
js屬性的方法
uj5u.com熱心網友回復:
使用key而不是keyCode
key是用戶想要看到的(對“A”持有 shift 或 capslock,或者對“a”不持有)
并利用該方法getAttribute
getAttributeElement 介面的方法回傳元素上指定屬性的值。
如果前一個元素不存在nullish (null 或 undefined) ,我也使用解構 和 可選鏈接來避免錯誤
var inputs = document.getElementsByClassName("test");
Array.from(inputs).forEach(function (input) {
input.addEventListener("keydown", keyhandler);
});
function keyhandler(e) {
let { key } = e;
let max = this.getAttribute("maxlength");
if (key == "Backspace") {
this.value = "";
this?.previousElementSibling?.focus();
e.preventDefault();
} else if (key == "Enter" || this.value.length >= max) {
this.nextElementSibling.focus();
}
}
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}
<input type="text" class="test" id="0" maxlength="1" />
<input type="text" class="test" id="1" maxlength="1" />
<input type="text" class="test" id="2" maxlength="1" />
<input type="text" class="test" id="3" maxlength="1" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/463307.html
標籤:javascript
下一篇:反應狀態下的語音識別問題
