本文介绍了达到最大长度值后,将下一个输入聚焦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果前一个输入达到最大长度值,我如何关注下一个输入?
How can I focus the next input once the previous input has reached its maxlength value?
a: <input type="text" maxlength="5" />
b: <input type="text" maxlength="5" />
c: <input type="text" maxlength="5" />
如果用户粘贴的文本大于maxlength,理想情况下它应该溢出到下一个输入中。
If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.
jsFiddle:
我必须强调我不想要使用插件,因为我更愿意学习这背后的逻辑,而不是使用已经存在的东西。感谢您的理解。
I must stress that I do not want to use a plugin, as I'd much rather learn the logic behind this, than use something that already exists. Thanks for understanding.
推荐答案
没有使用jQuery,这是一个非常干净的实现:
No jQuery used and is a very clean implementation:
- 从maxlength属性读取。
- 缩放到容器内的任意数量的输入。
- 自动查找下一个要聚焦的输入。
- 没有jQuery。
- Reads from the maxlength attribute.
- Scales to any number of inputs inside of your container.
- Automatically finds the next input to focus.
- No jQuery.
<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;
}
}
}
}
这篇关于达到最大长度值后,将下一个输入聚焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!