keydown on body?

前端 未结 5 1170
礼貌的吻别
礼貌的吻别 2020-12-20 22:53

I want to get alerted whenever I press a key.

I\'ve tried:

$(\'body\').live(\'keyup\', function() {
     alert(\'testing\');
});

Bu

相关标签:
5条回答
  • 2020-12-20 23:06

    It does not work because your page does not have focus.. you need to click on the page first and it will work..

    alternatively you could forcibly set the focus to an input element and thus bring focus to the page..

    $(function(){ $('input_selector_here').focus(); });
    
    0 讨论(0)
  • 2020-12-20 23:12

    Just listen to the window!

    $(window).keydown(function(event){
        alert(event.keyCode);
    });
    
    0 讨论(0)
  • 2020-12-20 23:22

    Hope this will help.

    $(document.body).on('keyup', function (e) {
        alert('In');
    }):
    
    0 讨论(0)
  • 2020-12-20 23:25

    Try using $("html") or $("*") instead of $("body"). In order for the keyUp event on body to fire, the body node or one of its children must be focused. You can accomplish this in your example by adding a text input and focusing the mouse to that input. What you really want is to capture any key press, so $("html") should work.

    Edit: I think your example might work, but in any case, to run the logic conditionally you might try this:

    if ($(document.body).is(".focusOnKeypress")) {
       $("html").live(...);
    }
    

    Or, I think this will also work:

    $("body:not(.noFocusOnKeypress)").parent("html").live(...);
    
    0 讨论(0)
  • 2020-12-20 23:28

    I tried this code. This is working fine.

    $('body').on('keyup', function() {
         alert('testing');
    });
    
    0 讨论(0)
提交回复
热议问题