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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

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:

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