最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does keypress() only fire when a textfield is focused in Firefox? - Stack Overflow

programmeradmin0浏览0评论
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

发布评论

评论列表(0)

  1. 暂无评论