jQuery: trigger keypress function on entire document but not inside inputs and textareas?

前端 未结 4 1792
无人共我
无人共我 2021-02-03 17:53

I have this …

$(document).keypress(function(e) {
        if ( e.keyCode === 119 ) // w
            doSomething();
    });

Wo when pressing \"w\

4条回答
  •  不要未来只要你来
    2021-02-03 18:13

    In jQuery, e.which is the normalized property, not e.keyCode.

    To check if you are not in an input you can check the document.activeElement:

    $(document).keypress(function(e) {
        if (e.which === 119 && !$(document.activeElement).is(":input,[contenteditable]")) {
            doSomething();
        }
    });
    

    Demo. http://jsfiddle.net/pxCS2/1/

提交回复
热议问题