jQuery's 'keypress' doesn't work for some keys in Chrome. How to work around?

后端 未结 6 788
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 12:20

I\'m trying to implement key-press functionality which will remove a div when the user hits Esc. This works for Firefox & IE with the following code:

<
相关标签:
6条回答
  • 2020-12-13 12:32

    For ESC key:

    $(document).keydown(function(e) {
      if(e.keyCode == 27) { /* Run code */ }
    }
    

    For letter keys, like 'L':

    $(document).keypress(function(e) {
      if(e.which == 108) { }
    });
    

    Works in both Chrome and Firefox

    0 讨论(0)
  • 2020-12-13 12:34

    use keydown. keypress doesn't work with ESC in Chrome (not sure about other browsers).

    $(newTag).keydown(function(e) {  //keypress did not work with ESC;
        if (event.which == '13') {
          ProfilePage.saveNewTag(search_id, $(newTag).val());
        }
        else if (window.event.which){
          $(newTag).remove();
        }
    }); 
    
    0 讨论(0)
  • 2020-12-13 12:35

    Try handling keydown instead.

    0 讨论(0)
  • 2020-12-13 12:36

    After the second alert add also

    e.preventDefault();
    

    This will prevent the default action of the event to be triggered.

    More info about this method here

    Your code should look like

    $("body").keypress(function(e) {
        alert("any key pressed");
        if (e.keyCode == 27) {
             alert("escape pressed");
             e.preventDefault();
    }});
    
    0 讨论(0)
  • keypress 'ESC'

    e.which: 0
    e.keyCode: 27
    

    keyup 'ESC'

    e.which: 27
    e.keyCode: 27
    

    For non-printable characters better use keyup.

    0 讨论(0)
  • 2020-12-13 12:52

    Using Jquery.hotkey js file you can Make Sortcut key

    $(document).bind('keydown', 'esc', function(){ });
    
    0 讨论(0)
提交回复
热议问题