keyEvent Property

事件对象参考手册Event Object

Examples

Get the keyboard key when a key is pressed:

var x = event.key;

xThe result is:

Enter

Try it Yourself »

More examples are included at the bottom of this article.


Definition and Usage

The key event returns the identifier of the key when a key is pressed.

The key identifier is a string representing the keyboard key. The return value of this property can be:

  • A single letter (e.g. "a", "W", "4", "+" or "$")
  • Multiple letters (e.g. "F1", "Enter", "HOME" or "CAPS LOCK")

Tip:If you want to check whether the "ALT", "CTRL", "META" or "SHIFT" key is pressed, you can use thealtKey, ctrlKey, metaKeyorshiftKeyproperty.


Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
key Not supported 9.0 23.0 Not supported Not supported


Syntax

event.key

Technical Details

Return Value: A string representing the keyboard key.

Possible values:
  • A single letter (e.g. "a", "W", "4", "+" or "$")
  • Multiple letters (e.g. "F1", "Enter", "HOME" or "CAPS LOCK")
Note:Chrome, Safari and Opera browsers return undefined
DOM Version: DOM Level 3 Events


实例

More Examples

Example

Pop up an alert message when the user presses the "A" key:

var x = event.key;

// If the "a" or "A" key is pressed (using caps lock or shift), pop up an alert message

if (x == "a" || x == "A") {
    alert ("You pressed the 'A' key!");
}

Try it Yourself »


Related Pages

HTML DOM Reference:key Event Property

HTML DOM Reference:charCode Event Property

HTML DOM Reference:which Event Property

事件对象参考手册Event Object

Other Extensions