Javascript 简明教程

JavaScript - Keyboard Events

JavaScript 中的键盘事件提供了一种基于用户键盘输入与网页或应用程序互动的方法。这些事件允许开发人员捕获和响应各种键盘操作,例如按键按下、按键松开和字符输入。JavaScript 中的主要键盘事件包括 keydown、keypress 和 keyup。

The keyboard events in JavaScript provide a way to interact with a web page or application based on the user’s keyboard input. These events allow developers to capture and respond to various keyboard actions, such as key presses, key releases, and character inputs. The primary keyboard events in JavaScript include keydown, keypress, and keyup.

Common Keyboard Events

  1. Keydown Event − When a key on the keyboard is pressed down, it triggers the keydown event. This event equips developers with information about the specific key that was pressed: this includes its code and an indicator of whether certain modifier keys such as Shift, Ctrl, or Alt were also depressed.

  2. Keypress Event − The keypress event triggers when a user types an actual character. Non-character keys, such as Shift or Ctrl, do not activate this event. Developers frequently utilize it to capture user input for form fields or create interactive typing features.

  3. Keyup Event − Upon the release of a previously pressed key, the system initiates the firing of a keyup event; this particular event proves beneficial in tracking specific keys' releases and subsequently implementing actions, thereby creating an interactive user experience.

Keyboard Event Properties

对于 JavaScript 中的键盘事件,几个属性通常用于收集有关所按按键的信息。以下是一些与键盘事件特别相关的关键属性−

For keyboard events in JavaScript, several properties are commonly used to gather information about the key pressed. Here are some key properties specifically relevant to keyboard events −

Property

Description

event.key

String representing the key value of the pressed key.

event.code

String representing the physical key on the keyboard.

event.location

Integer indicating the location of the key on the keyboard.

event.ctrlKey

Boolean indicating whether the Ctrl key was held down.

event.shiftKey

Boolean indicating whether the Shift key was held down.

event.altKey

Boolean indicating whether the Alt key was held down.

event.metaKey

Boolean indicating whether the Meta (Command) key was held down.

event.repeat

Boolean indicating whether the key event is a repeat event.

event.isComposing

Boolean indicating whether the event is part of a composition of multiple keystrokes.

event.which

Deprecated property; previously used to identify the numeric key code.

event.getModifierState(keyArg)

Method that returns a boolean indicating whether the modifier key is pressed.

Example: Keydown Event

此示例说明了 JavaScript 的 keydown 事件的应用。当按下任何键时,事件侦听器将获取 keydown 事件,并在标识为“output”的 HTML 元素中显示其对应的键(事件属性)。

This example illustrates the application of JavaScript’s keydown event. The event listener seizes the keydown event upon pressing any key, displaying in an HTML element identified as "output" - its corresponding key (an event property).

<!DOCTYPE html>
<html>
<body>
   <h3>Press any key</h3>
   <script>
      document.addEventListener('keydown', function (event) {
         document.getElementById('output').innerHTML =
		 "Key pressed: " + event.key;
      });
   </script>
   <div id="output"></div>
</body>
</html>

Example: Keypress Event

在此示例中,keypress 事件用于捕获已键入字符。当键入字符时,事件侦听器将触发,并且该字符将显示在具有 id“output”的 HTML 元素中。

In this example, the keypress event is utilized to capture a typed character. When a character is typed, the event listener triggers, and the character is displayed in the HTML element with the id "output".

<!DOCTYPE html>
<html>
<body>
   <h3>Type a character</h3>
   <div id="output"></div>
   <script>
      document.addEventListener('keypress', function (event) {
         document.getElementById('output').innerHTML =
         "Character pressed: " + event.key;
      });
   </script>
</body>
</html>

Example: Keyup Event

此示例展示了 keyup 事件。当释放被按下的键后,它会捕获事件。然后在屏幕上显示已释放的键。

The keyup event is showcased in this example. It captures the event when a key is released after being pressed. The released key is then displayed on screen.

<!DOCTYPE html>
<html>
<body>
   <h3>Press and Release a key</h3>
   <div id="output"></div>
   <script>
      document.addEventListener('keyup', function (event) {
         document.getElementById('output').innerHTML =
		 "Key released: " + event.key;
      });
   </script>
</body>
</html>

keydown 和 keypress 之间存在差异。当按下任何键时,将触发 keydown,它将提供有关所按键的信息,包括修饰键。当按下字符键时,将专门触发 keypress,它将提供有关已键入字符的信息,但不提供有关修饰键的详细信息。只要按住该键,keydown 就会持续触发。

There is a difference between keydown and keypress. keydown is triggered when any key is pressed down, providing information about the pressed key, including modifiers. keypress is triggered specifically when a character key is pressed, providing information about the typed character without details on modifiers. Keydown fires continuously as long as the key is held down.

在以上所有示例中,我们都已使用 addEventListener,但无需此函数也可侦听这些事件。这是因为您可以直接将事件处理程序分配给特定属性。但是,请记住,通常将使用 addEventListener 视为一个更好的做法,因为它允许您将多个事件处理程序附加到同一事件,并且它将 JavaScript 逻辑与 HTML 结构分开。

In all the above examples, we have used the addEventListener but these events can be listened to without this function as well. This is because of you can assign event handlers directly to specific properties. However, keep in mind that using addEventListener is generally considered a better practice because it allows you to attach multiple event handlers to the same event, and it separates JavaScript logic from the HTML structure.

Example: Without using addEventListener method

在此示例中,我们有一个输入框。当它检测到 keydown 事件(onkeydown)时,将调用 handleKeyDown 函数,当它检测到 keyup 事件(onkeyup)时,将调用 handleKeyUp 函数。这两个函数都会将适当的消息打印到屏幕上。

In this example, we have an input box. When it detects a keydown event (onkeydown), the handleKeyDown function is called and when it detects a keyup event (onkeyup) it calls the handleKeyUp function. Both the functions print appropriate messages to the screen.

<!DOCTYPE html>
<html>
<body>
   <div>Enter some text:
      <input onkeydown="handleKeyDown(event)" onkeyup="handleKeyUp(event)">
   </div>
   <div id="output"></div>
   <script>
      function handleKeyDown(event) {
         document.getElementById('output').innerHTML+=
		 "Key pressed: " + event.key+'<br>Key code: ' + event.keyCode+'<br>';
      }
      function handleKeyUp(event) {
         document.getElementById('output').innerHTML+=
		 "Key released: ' + event.key+'<br><br>";
      }
   </script>
</body>
</html>