keypress() 是否仅在 Firefox 中文本字段聚焦时触发?
jQuery(document).ready(function ($) {
$('body').keypress(function (e) {
alert(e.which);
});
});
在 Chrome 中按下某个键时会弹出警报,但在 Firefox 中则不会。但是,如果我创建一个文本字段并将其聚焦,然后按一个键,Firefox 中会弹出警报。 (尽管 $('body') 仍然是 jQuery 对象。)
即使文本字段没有聚焦,我怎样才能在 Firefox 中触发该事件?有解决方法吗?当在页面上的任意位置按下 Enter 键时,我将触发一个事件。
谢谢大家
jQuery(document).ready(function ($) {
$('body').keypress(function (e) {
alert(e.which);
});
});
This will pop up an alert when a key is pressed in Chrome but not in Firefox. However, if I create a text field and focus it, then press a key, an alert will pop up in Firefox. (Even though $('body') is still the jQuery object.)
How can I get the event to fire in Firefox even when a textfield is not focused? Is there a workaround? I will be firing an event when the Enter key is pressed anywhere on the page.
Thanks guys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果页面上没有元素,浏览器可能会认为
元素(或其任何子元素)没有焦点。尝试将您的事件绑定到文档:
If you have no elements on the page, the browser might assume that the
<body>
element (or any of its descendants) doesn't have focus. Try binding your event to the document:@DarthJDG 是对的,但是如果您想在页面加载后立即监听按键,您仍然应该将焦点设置在窗口上。在某些情况下,浏览器会将焦点保留在地址栏上。所以添加:
设置按键处理程序后
@DarthJDG is right, but you should still set focus on the window if you want to listen for keypresses immidiately after page load. in some cases browsers will leave focus on the address bar. so add:
after setting up the keypress handler