网页是否可以在没有文本输入字段或文本输入字段未集中的情况下检测键盘输入?
add an event listener to the document (run the example, and click on it to activate it, otherwise its document won't have the focus, this is intended to work on a standalone page rather than embedded frame)
document.addEventListener('keydown', keydownCallback, false); function keydownCallback(e) { console.log(e.keyCode + ': "' + String.fromCharCode(e.keyCode) + '"'); }
You can add onkeydown
handler on document
, you just need to have the focus on the window.
document.onkeydown = function(e) { switch (e.keyCode) { case 37: console.log('left'); break; case 38: console.log('up'); break; case 39: console.log('right'); break; case 40: console.log('down'); break; } };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.