想问一下..假设我有3个输入示例,其中字符的最大长度不同。
<input type="text" name="text1">
<input type="text" name="text2">
<input type="text" name="text3">
如果我输入字符123456789,那么当我在第一个输入中填入数字12时,会自动移动到第二个输入。如何 ?还是javascript名称?
答案 0 :(得分:3)
这是一个非常干净的实现,您需要:
<div class="container">
a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />
</div>
..
var container = document.getElementsByClassName("container")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
}