Home  >  Article  >  CMS Tutorial  >  JavaScript: Mastering Keyboard Event Handling

JavaScript: Mastering Keyboard Event Handling

PHPz
PHPzOriginal
2023-09-04 11:29:021195browse

JavaScript: Mastering Keyboard Event Handling

Website developers want readers to interact with their website in some way. Visitors can scroll up and down the page, write in input fields, click a link to access another page, or press key combinations to trigger specific actions. As a developer, you should be able to capture all these events and provide the required functionality to the user.

In this tutorial, our focus will be on handling keyboard events in JavaScript. We'll learn about the different types of keyboard events, handling special key events, and getting information about keys that are pressed or released.

Keyboard event type

Keyboard events are divided into three types. These are called keydown, keypress, and keyup.

As long as a key is pressed, the keydown event will be triggered. All keys will be triggered. It doesn't matter whether they generate character value. For example, pressing the A or Alt key on the keyboard will trigger the keydown event.

keypress event is deprecated. It only fires when the key that produces the character value is pressed. For example, pressing the A key will trigger this event, but pressing the Alt key will not. You should consider using the keydown event instead.

When the key pressed by the user is released, the keyup event will be triggered.

Suppose the user presses any key on the keyboard continuously. In this case, the keydown event will be triggered repeatedly. Once the user releases the key, the keyup event is triggered.

Listen to keyboard events

At this point, I want to mention something fairly obvious. A keyboard is an input device used to get some input from the user. We take action based on that input. However, there are other ways for users to send input.

If you want to track any input fields that the user fills out in a form, it makes more sense to use other events on said inputs (such as change ).

Additionally, keyboard events are generated only for elements that can receive focus. This includes <input> elements, <textarea></textarea> elements, <summary></summary> elements, and elements with contentEditable or tabindex Other elements of attributes.

For example, you cannot listen to keyboard events on a paragraph element unless you set the tabindex or contentEditable properties. However, it will eventually bubble up in the DOM tree, so you can still attach a keydown or keyup event listener to the document.

This is an example:

document.addEventListener("keydown", keyIsDown);

function keyIsDown(event) {
    // Do whatever you want!
}

You can also provide the callback as an arrow function:

document.addEventListener("keydown", (event) => {
    // Do whatever you want!
});

Get information from keyboard events

In the basic code snippet of the previous section, we defined a callback function. This function accepts an event object as its argument. This event object contains all the information you might need to access related to the keydown or keyup event.

Here are some useful properties you should know about:

  1. key: This property returns a string representing the character value of the key pressed.
  2. code: This property returns a string representing the code of the physical key pressed.
  3. repeat: If a key is pressed for a long time, this property will return a Boolean value true, causing the keydown event to be triggered multiple times.
  4. altKey: If the user presses the Alt key (on Windows) or the Option key (on macOS) when When the keydown event is triggered.
  5. ctrlKey: If the user presses the Control key when the keydown event fires, this property returns a Boolean value true.
  6. metaKey: If the user presses the Meta key when the keydown event fires, this property returns a Boolean value true.
  7. shiftKey: If the user presses the Shift key when the keydown event fires, this property returns a Boolean value true.

You'll notice that I've included the "when the keydown event is fired" part in all the last four property descriptions. This means that if a key such as A or 3 is pressed while performing any of the above actions, the value of these properties will be true for keydown event. The key is also pressed.

After focusing on the following CodePen demo, try pressing individual keys or key combinations to see the values ​​of different properties change.

如果您按键盘顶部的 3 键而不按 Shift 键,则 key 属性的值将变为 3 > 并且 code 属性的值变为 Digit3。但是,按下 Shift 后,key 属性的值将变为 #,而 code 属性仍为 Digit3

您可以尝试使用其他组合键进行相同的操作,您会注意到 key 属性的值会根据您按下的键而变化。但是,code 属性的值保持不变。

键盘上的某些键通常是重复的。例如,有两个 Shift 键。按左键会将 code 的值设置为 ShiftLeft。按右边会将 code 的值设置为 ShiftRight。同样,有两组数字键。字母上方的代码将为您提供 Digit<number></number> 代码,而数字键盘上的代码将为您提供 Numpad<number></number> 代码。

这意味着,如果您的代码依赖于检测特定键,则务必确保您使用 code 属性来检查按下了哪个键。

我想提的另一件重要的事情是,并不是每个人都使用 QWERTY 键盘,而且他们的键盘甚至可能不是英文的。在这种情况下,使用 key 属性来检查按下了哪个键很容易出错。

响应键盘事件

现在我们知道了如何监听键盘事件并从中提取信息,我们可以编写一些代码来对某些特定键的 keydownkeyup 事件做出反应。考虑以下代码片段:

const circle = document.querySelector(".circle");

document.addEventListener("keydown", (event) => {
    
  if (event.code == "KeyR" && event.repeat != true) {
    let rVal = Math.floor(200 + Math.random() * 200);
    circle.setAttribute("style", `width: ${rVal}px; height: ${rVal}px;`);
  }

  if (event.key == "B" && event.shiftKey == true) {
    let rVal = Math.floor(10 + Math.random() * 40);
    circle.setAttribute("style", `border: ${rVal}px solid orangered;`);
  }

  if (event.code == "ArrowUp" && event.repeat != true) {
    circle.classList.add("animate__animated", "animate__bounce");
  }
});

document.addEventListener("keyup", (event) => {
  if (event.code == "ArrowUp") {
    setTimeout(() => {
      circle.classList.remove("animate__animated", "animate__bounce");
    }, 4000);
  }
});

我们为 keydown 事件创建了一个侦听器,并为 keyup 事件创建了另一个侦听器。这两个事件都附加到 document

keydown 内,我们检查三个不同的密钥。我使用了 R 键的 event.code 属性来向您展示您可以单独按 R 键或与任何修饰键组合使用,并且它仍会将圆的半径更改为随机值。另一方面,我们使用 event.key 属性来检查其值是否为 B。仅当您同时按 ShiftB 时,此块中的代码才会执行​​,因为这种组合会导致 event.key 属性成为大写“B”。

keyup 内,我们检查 ArrowUp 键上的 keyup 事件。一旦钥匙被解除,我们会在四秒的延迟后删除之前附加的类。

以下 CodePen 演示展示了这一切的实际效果:

您应该尝试在上述代码中添加自己的逻辑,以便当用户按下ASW键时圆圈会移动> 和D

最终想法

在本教程中,我们学习了 JavaScript 中键盘事件的基础知识。按下并释放键盘上的按键将分别触发 keydownkeyup 事件。与这些事件关联的 event 对象包含您确定按下了哪个键并采取适当操作所需的所有信息。

请记住,键盘只是众多可能的输入设备之一。因此,使用键盘检测任何输入可能并不总是能达到预期效果。在这种情况下,您应该考虑使用与输入相关的事件。

The above is the detailed content of JavaScript: Mastering Keyboard Event Handling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn