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

后端 未结 6 805
伪装坚强ぢ
伪装坚强ぢ 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: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();
    }});
    

提交回复
热议问题