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

前端 未结 5 1596
时光说笑
时光说笑 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 03:55

    For modern JS, use event.key!

    document.addEventListener("keypress", function onPress(event) {
        if (event.key === "z" && event.ctrlKey) {
            // Do something awesome
        }
    });
    

    NOTE: The old properties (.keyCode and .which) are Deprecated.

    Mozilla Docs

    Supported Browsers

提交回复
热议问题