Capture key press without placing an input element on the page?

前端 未结 5 1607
时光说笑
时光说笑 2020-11-27 03:12

How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input el

5条回答
  •  清酒与你
    2020-11-27 04:02

    For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.

    Attaching a keydown event to document works in all the major browsers:

    document.onkeydown = function(evt) {
        evt = evt || window.event;
        if (evt.ctrlKey && evt.keyCode == 90) {
            alert("Ctrl-Z");
        }
    };
    

    For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.

提交回复
热议问题