简体   繁体   English

专注于输入类型文本/按键搜索

[英]Keep focus on input type text/search on keypress

I've written a simple input of type text, but when I press enter while my cursor is inside the textbox, it looses the focus. 我已经编写了一个简单的文本类型输入,但是当光标在文本框中时按Enter键,则会失去焦点。 How can I ignore enter key to stop losing focus from the text box? 如何忽略Enter键以停止失去文本框的焦点? I tried doing something like this: 我试图做这样的事情:

<input type="text" (keyup)="keepFocus($event)" />

and keepFocus() is a method: 而keepFocus()是一种方法:

keepFocus(e) {
 e.target.select();
}

But this method is called everytime I press a key, which is not very efficient. 但是,每次我按一个键时都会调用此方法,这不是很有效。 Is there a better solution to handle this behavior? 是否有更好的解决方案来处理此行为?

You capture just the enter key, and prevent default when it's pressed 您仅捕获Enter键,并防止在按下时默认

 document.getElementById('myInput').addEventListener('keypress', function(event) { if (event.which === 13) event.preventDefault(); }); 
 <input type="text" id="myInput" /> 

Another way to do this is by getting the keyCode (that e parameter use). 另一种方法是通过获取keyCodee参数使用)。

I mean, use this: 我的意思是,使用这个:

http://www.javascripter.net/faq/keycodes.htm http://www.javascripter.net/faq/keycodes.htm

And this: 和这个:

https://www.w3schools.com/jsreF/event_preventdefault.asp https://www.w3schools.com/jsreF/event_preventdefault.asp

Something like this would be fine: 这样的事情就可以了:

  function keepFocus(e) { if(e.keyCode == 13) e.preventDefault(); } 
  <input type="text" keyup="keepFocus" /> 

This will prevent that you lost the focus when enter key is pressed! 这样可以防止您在按Enter键时失去焦点!

There are two ways to do the job. 有两种方法可以完成这项工作。

First, reput the focus to the input when the user click "Enter": 首先,在用户单击“ Enter”时将焦点放在输入中:

<input type="text" onkeyup="keepFocus(event);" id="teste" />
function keepFocus(e) {
    if (e.key=="Enter") {
      var teste = document.getElementById ("teste");
      teste.focus ();
  }
}

Second, prevent the default behavior of the text field: 其次,防止文本字段的默认行为:

function keepFocus(e) {
   if (e.key=="Enter") {
     e.preventDefault ();
  }
}

I think the second way is better because you do not have to add an id to your input. 我认为第二种方法更好,因为您不必在输入中添加id。

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

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