当用户快速键入时,焦点会跳过

Focus Skips When User Types Fast

本文关键字:焦点 用户      更新时间:2023-09-26

我一直在处理网页上的日期输入。我将日期作为三个输入字段。计划是在第一个字段中键入两个字符时,焦点将自动转到下一个字段,并且将选择该字段中的所有文本。在此字段中键入 2 位数字后,下一个字段将自动聚焦。我在onkeyup上使用javascript函数工作。HTML 是(日期对我来说是日-月-年格式):

    <input id="dobDay" style="width:30px" maxlength="2"
        onkeyup="CheckIfFieldIsFull(event, this, 2, dobMonth)"
        onfocus="this.select();" onmouseup="return false;"
        >
    /
    <input id="dobMonth" style="width:30px;" maxlength="2"
        onkeyup="CheckIfFieldIsFull(event, this, 2, dobYear)"
        onfocus="this.select();" onmouseup="return false;"
        >
    /
    <input id="dobYear" style="width:50px" maxlength="4" 
        onkeyup="CheckIfFieldIsFull(event, this, 4, IdOfNextField)"
        onfocus="this.select();" onmouseup="return false;"
        >

和JavaScript:

function CheckIfFieldIsFull(e, CurrentField, MaxChars, IDOfNextField) {
  if (e.keyCode != 9 && 
      CurrentField.value.length >= MaxChars)
  {
    document.getElementById(IDOfNextField.id).focus();
  }
}

这一切都在正常打字速度下按要求工作。如果字段已经填充了一些数据,并且用户在第一个字段中快速键入 2 个不同的字符,那么光标不在第二个字段中,它将跳转到第三个字段:-(

将给予焦点的字段为空或其中只有 1 个字符时,不会发生这种情况,仅当字段中已包含最大长度字符时才会发生这种情况。

我很确定这是因为在用户点击第二个键时,第一个键还没有执行键up事件。我这样说是因为如果您在第一个字段中尽可能快地键入两个相同的字符,则不会出现问题(当它是相同的物理键时,您无法在上一个键键发生之前进行按键)。

任何想法是什么导致了这个问题或如何避免它?

告诉用户打字慢一点?!

我已经尝试了onkeypress()而不是onkeyup(),但它还有其他问题(主要是CurrentField.value不会更新以反映刚刚按下的键,因此长度不会给出任何相关内容)。

感谢您的任何帮助。

试试这个。 http://jsfiddle.net/t1zfp8ma/

新链接 http://jsfiddle.net/t1zfp8ma/6/

<input class="date" id="dobDay" style="width:30px" maxlength="2">/
<input class="date" id="dobMonth" style="width:30px;" maxlength="2">/
<input class="date" id="dobYear" style="width:50px" maxlength="4">
$('.date').keyup(function (e) {
if($(this).val().length == 2 && $(this).hasClass('dirty')){
    $(this).removeClass('dirty');
    $(this).next().removeClass('dirty').select();
}
}).keydown(function(e){
    $(this).addClass('dirty');
})

另一种方法是使用keydown事件和setTimeout来定义值和移动焦点:

.HTML:

<input id="dobDay" style="width:30px" maxlength="2" onkeydown="CheckIfFieldIsFull(event, this, 2, dobMonth)" onfocus="this.select();" onmouseup="return false;" > / <input id="dobMonth" style="width:30px;" maxlength="2" onkeydown="CheckIfFieldIsFull(event, this, 2, dobYear)" onfocus="this.select();" onmouseup="return false;" > / <input id="dobYear" style="width:50px" maxlength="4" onfocus="this.select();" onmouseup="return false;" >

.JS:

window.CheckIfFieldIsFull = function (e, CurrentField, MaxChars, IDOfNextField) { setTimeout(function () { if (e.keyCode != 9 && CurrentField.value.length >= MaxChars) { var next = document.getElementById(IDOfNextField.id); next.focus(); } }, 0); }

http://jsfiddle.net/f5sesoay/2/

如果我在

关注下一个字段之前重置值,这对我们有用

var next = document.getElementById(IDOfNextField); next.value = ''; next.focus();

http://jsfiddle.net/f5sesoay/