从键盘事件获取键值

将事件处理程序绑定到键盘操作并检索触发事件的键值


要获取键码(按钮的值),需要将事件处理程序附加到任何键盘操作上。 在处理程序函数接收到的事件对象上报告键代码。


// event handler function
function handler(e) {
    var key = window.event ? e.keyCode : e.which;
    console.log(key, e.shiftKey, e.altKey, e.ctrlKey);
}

// attach handler to the keydown event of the document
if (document.attachEvent) document.attachEvent('onkeydown', handler);
else document.addEventListener('keydown', handler);
      

可以在DOM元素上使用任何键盘事件keypress,keydown,keyup。例如文本输入字段或textareas。