admin管理员组文章数量:1428481
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
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
Share Improve this question asked May 23, 2011 at 2:05 NathanNathan 5,3725 gold badges26 silver badges25 bronze badges2 Answers
Reset to default 7If 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:
jQuery(document).ready(function ($) {
$(document).keypress(function (e) {
alert(e.which);
});
});
@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:
$(window).focus();
after setting up the keypress handler
本文标签: javascriptDoes keypress() only fire when a textfield is focused in FirefoxStack Overflow
版权声明:本文标题:javascript - Does keypress() only fire when a textfield is focused in Firefox? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745528973a2661972.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论