键盘事件监听
There are 3 types of events when interacting with keyboard events:
与键盘事件进行交互时,有3种类型的事件:
keydown
the keyboard key has been pressedkeydown
键盘键被按下keyup
the keyboard key has been releasedkeyup
键盘按键已被释放
keydown
is also fired when the key repeats while the button stays pressed.
keydown
也发射时的键重复而按钮保持按下。
While mouse and touch events are typically listened on a specific element, it’s common to listen for keyboard events on the document:
尽管通常在特定元素上侦听鼠标和触摸事件,但在文档上侦听键盘事件是很常见的:
document.addEventListener('keydown', event => {
// key pressed
})
The parameter passed to the event listener is a KeyboardEvent.
传递给事件侦听器的参数是KeyboardEvent 。
This event object, in addition to the Event object properties offers us (among others) these unique properties:
除了“ 事件”对象的属性外,该事件对象还为我们提供了以下这些独特的属性:
altKey
true if alt key was pressed when the event was firedaltKey
如果触发事件时按下alt键,altKey
truecode
the code of the key pressed, returned as a stringcode
所按下键的编码,以字符串形式返回ctrlKey
true if ctrl key was pressed when the event was firedctrlKey
如果触发事件时按下ctrl键,则为truekey
the value of the key pressed, returned as a stringkey
所按下key
的值,以字符串形式返回locale
the keyboard locale valuelocale
键盘语言环境值location
the location of the key on the keyboardlocation
键盘上按键的位置metaKey
true if meta key was pressed when the event was firedmetaKey
如果触发事件时按下了meta键,metaKey
truerepeat
true if the key has been repeated (e.g. the key has not been released)repeat
如果该键已经被重复真(如钥匙尚未发布)shiftKey
true if shift key was pressed when the event was firedshiftKey
如果触发事件时按下Shift键,则为true
This demo is a keylogger which will show you the values of some of the properties I listed above:
该演示是一个键盘记录程序,它将向您显示我上面列出的某些属性的值:
See the Pen Key logger demo by Flavio Copes (@flaviocopes) on CodePen.
见笔键盘记录演示由弗拉维奥科佩斯( @flaviocopes上) CodePen 。
键盘事件监听