📜  javascript onkeydown - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:38.140000             🧑  作者: Mango

JavaScript Onkeydown

JavaScript onkeydown is an event that triggers when a keyboard key is pressed down. This event captures the key code and can be used to perform actions based on the key that was pressed.

Syntax

The syntax for using onkeydown in JavaScript is as follows:

element.onkeydown = function(event) {
  // code to be executed when a key is pressed down
};

The onkeydown event should be attached to a specific element, typically an input field, textarea or the document object. The event parameter in the function contains information about the key that was pressed.

Example

Here is an example of using onkeydown to detect when the enter key (key code 13) is pressed in an input field:

<!DOCTYPE html>
<html>
<head>
  <title>Onkeydown Example</title>
</head>
<body>

  <input type="text" id="input-field">

  <script>
    let input = document.getElementById("input-field");
    input.onkeydown = function(event) {
      if (event.keyCode === 13) {
        console.log("Enter key pressed!");
      }
    };
  </script>

</body>
</html>

In this example, we first select the input element using the getElementById method. We then attach an onkeydown event to the input element that will trigger when a key is pressed down. We use an if statement to check if the key code is 13, which corresponds to the enter key. If it is, we print a message to the console.

Conclusion

The onkeydown event in JavaScript is a powerful tool for capturing user input from the keyboard. By using this event, you can create interactive applications that respond to user input in real-time.