文档
事件类型
- keydown
- keypress
- keyup
属性 | 类型 | windows | Mac OS |
altKey | Boolean | Alt | Option、⌥ |
ctrlKey | Boolean | Ctrl | control、^ |
shiftKey | Boolean | shift | shift |
metaKey | Boolean | - | Command、⌘ |
key | String | - | - |
keyCode (Deprecated) | String | - | - |
代码示例
<div id="text"></div> <script> function eventHandler(event) { console.log(event); let data = { code: event.code, key: event.key, keyCode: event.keyCode, altKey: event.altKey, shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, }; let list = []; for (let [key, value] of Object.entries(data)) { list.push(`<li>${key}: ${value}</li>`); } document.querySelector("#text").innerHTML = list.join(""); } document.addEventListener("keydown", this.eventHandler.bind(this)); </script>
在线体验:https://github.com/mouday/front-end-demo/EventListener-keydown.html