简体   繁体   English

在keydown事件之后关注字段而不插入字符

[英]Focus on field after keydown event without inserting character

I have a shortcut key K . 我有一个快捷键K. It should focus on my input, but I don't want it to insert the letter K when it focuses. 它应该专注于我的输入,但我不希望它在焦点时插入字母K

 $(document).keydown(function(event) { if (event.which == 75) { $('input').focus(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type="text"> 

You can use event.preventDefault() to stop the standard behaviour of the event. 您可以使用event.preventDefault()来停止事件的标准行为。 Note however that this will stop the letter K from being able to be typed in the input . 但请注意,这将阻止字母K在输入中input To allow that you need to add a keydown handler to the input itself which stops the event propagation reaching the document . 为此,您需要向input本身添加keydown处理程序,以阻止事件传播到达document Try this: 尝试这个:

 $(document).keydown(function(event) { if (event.which == 75) { event.preventDefault(); $('input').focus(); } }); $('input').keydown(function(e) { e.stopPropagation(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type="text"> 

This is another way: 这是另一种方式:

At the time of keydown, if it is k and the input does not have focus then prevent the default behavior and give focus to the text field. 在keydown时,如果它是k并且输入没有焦点,则阻止默认行为并将焦点放在文本字段上。

 $(document).keydown(function(event) { if (event.which == 75 && !$('input').is(":focus")) { event.preventDefault(); $('input').focus(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type="text"> 

If you want to abruptly stop the propagation, you can also use return false; 如果你想突然停止传播,你也可以使用return false; :

 $(document).keydown(function(event) { if (event.which == 75) { $('input').focus(); return false; } }); $('input').keydown(function(e) { e.stopPropagation(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type="text"> 

var input = $('input');

$(document).on('keyup', function (e) {
  if(input.is(':focus')){
    return;
  }
  if (e.which == 75) {
        input.focus();
    }
});
  1. Listen to the keyup event; 听取keyup事件;
  2. If the input is already focused, don't focus again. 如果输入已经聚焦,请不要再次聚焦。

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

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