gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:35:02 24 4
gpt4 key购买 nike

我一直在网页上输入日期。我将日期作为三个输入字段。该计划是,当在第一个字段中输入两个字符时,焦点会自动转到下一个字段,并且该字段中的所有文本都将被选择。当在此字段中输入 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 个字符时,不会发生这种情况,仅当字段中已包含 maxlength 个字符时才会发生这种情况。

我很确定这是因为当用户按下第二个键时第一个键尚未完成 keyup 事件。我这样说是因为如果您尽快在第一个字段中输入两个相同的字符,则不会出现问题(当它是相同的物理键时,您无法在上一个按键发生之前按下按键)。

有什么想法导致此问题或如何避免它吗?

告诉用户打字慢一点?!

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

感谢您的帮助。

最佳答案

试试这个。 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');
})

关于javascript - 当用户快速键入时焦点会跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com