js onkeydown
时间: 2023-10-04 09:04:20 浏览: 60
javascript onkeydown实现键盘快捷键控制页面.docx
The onkeydown event in JavaScript is triggered when a key is pressed down on the keyboard. It can be used to perform certain actions or trigger certain events in response to user input.
The syntax for using onkeydown event is as follows:
```
element.onkeydown = function(event) {
// code to be executed
};
```
Here, "element" refers to the HTML element that you want to attach the event to, and "event" is an object that contains information about the key that was pressed (such as the keyCode, which represents the numeric value of the pressed key).
Example code:
```
document.onkeydown = function(event) {
if (event.keyCode == 13) {
alert("You pressed the Enter key!");
}
};
```
In this example, the onkeydown event is attached to the entire document object. When the user presses a key, the function checks if the keyCode is equal to 13 (which represents the Enter key). If it is, an alert message is displayed.
阅读全文