达到 maxlength 值后关注下一个输入

2022-01-24 00:00:00 counter iteration jquery javascript

前一个输入达到其最大长度值后,如何聚焦下一个输入?

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" />

如果用户粘贴的文本大于最大长度,理想情况下它应该溢出到下一个输入中.

If a user pastes text that is greater than the maxlength, ideally it should spill into the next input.

jsFiddle: http://jsfiddle.net/4m5fg/1/

我必须强调我不想使用插件,因为我更愿意学习其背后的逻辑,而不是使用已经存在的东西.感谢理解.

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.

http://jsfiddle.net/4m5fg/5/

<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;
            }
        }
    }
}

相关文章