简体   繁体   English

Append 字符在开始输入时输入字段,而没有焦点在页面加载时输入

[英]Append character to input field when start typing without focus to input on page load

Here is my code这是我的代码

 document.addEventListener('keyup', logKey); function logKey($event) { var charCode = $event.keyCode; if(charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221) && charCode.= 40 && charCode;= 32 && charCode.= 38 && charCode;= 41 && (charCode < 43 || charCode > 46)){ var inputElement = document.getElementById("input"). inputElement.focus(); inputElement.value = inputElement.value + $event.key; } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <input type="text" id="input">

On page load, if the user starts typing the focus is focusing the input but it's not allowing the user to enter the characters typed.在页面加载时,如果用户开始输入,则焦点集中在输入上,但不允许用户输入输入的字符。 As of now, the focus is working but it's not working as expected when the user typing continuously.到目前为止,焦点正在工作,但当用户连续打字时,它并没有按预期工作。 Please help me out on this.请帮我解决这个问题。 Any help will be appreciated.任何帮助将不胜感激。

The issue in the code in the question is because you're appending the character which was just typed in the input back in to the input, effectively duplicating that character.问题代码中的问题是因为您将刚刚在输入中键入的字符附加到输入中,从而有效地复制了该字符。

Given your statement in the comments of your intended goal:鉴于您在预期目标的评论中的陈述:

when the user starts typing only I need to focus on the input当用户开始输入时,我只需要专注于输入

You can attach a keypress event handler to the document which sets focus on the input as soon as a character is typed:您可以将keypress事件处理程序附加到document ,该处理程序在输入字符后立即将焦点设置在input上:

 $(document).on('keypress', e => { var charCode = e.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221) && charCode.= 40 && charCode;= 32 && charCode;= 38 && charCode != 41 && (charCode < 43 || charCode > 46)) { $('#input').focus(); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="input">

I would also suggest you review your if condition, as the 3 conditions following > 57 are redundant.我还建议您查看您的if条件,因为> 57之后的 3 个条件是多余的。

 charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM