簡體   English   中英

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

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

我有一個快捷鍵K. 它應該專注於我的輸入,但我不希望它在焦點時插入字母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"> 

您可以使用event.preventDefault()來停止事件的標准行為。 但請注意,這將阻止字母K在輸入中input 為此,您需要向input本身添加keydown處理程序,以阻止事件傳播到達document 嘗試這個:

 $(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"> 

這是另一種方式:

在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"> 

如果你想突然停止傳播,你也可以使用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. 聽取keyup事件;
  2. 如果輸入已經聚焦,請不要再次聚焦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM