捕获在页面上任何地方按下的Enter键


87

我需要随时在登录页面上的任意位置捕获Enter键。它将启动登录尝试。

使用jQuery,我该如何完成?我可以将其链接到body标签吗?

Answers:


145
$(document).keypress(function(e) {
  if(e.which == 13) {
    // enter pressed
  }
});

5
我正在尝试此操作,但我发现并没有为箭头键触发按键,而是按下了按键!
akotian 2014年

@akotian:非常正确!但是,我喜欢从独木舟的答案中对按键和按键的更早,更完整的描述。
HoldOffHunger

30

按下键时会触发keydown事件。
当按下某个键时会触发keypress事件,并且该键通常会产生一个字符值。

$(document).keydown( function(event) {
  if (event.which === 13) {
    // login code here
  }
}); 

1
效果比更好keypress。例如,我可以keypress 检测出何时按下ESC键。但是keydown效果很好。谢谢!
Wis Wisz Laszlo
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.