Table of Contents
Keyboard event type
Listen to keyboard events
Get information from keyboard events
响应键盘事件
最终想法
Home CMS Tutorial WordPress JavaScript: Mastering Keyboard Event Handling

JavaScript: Mastering Keyboard Event Handling

Sep 04, 2023 am 11:29 AM

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:

1

2

3

4

5

document.addEventListener("keydown", keyIsDown);

 

function keyIsDown(event) {

    // Do whatever you want!

}

Copy after login

You can also provide the callback as an arrow function:

1

2

3

document.addEventListener("keydown", (event) => {

    // Do whatever you want!

});

Copy after login

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> 代码,而数字键盘上的代码将为您提供 Numpad<Number> 代码。

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

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

响应键盘事件

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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);

  }

});

Copy after login

我们为 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Embed and Protect PDF Files With a WordPress Plugin How to Embed and Protect PDF Files With a WordPress Plugin Mar 09, 2025 am 11:08 AM

This guide demonstrates how to embed and protect PDF files within WordPress posts and pages using a WordPress PDF plugin. PDFs offer a user-friendly, universally accessible format for various content, from catalogs to presentations. This method ens

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress? Why would anyone use WordPress? Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

Is WordPress still free? Is WordPress still free? Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Is WordPress a CMS? Is WordPress a CMS? Apr 08, 2025 am 12:02 AM

WordPress is a Content Management System (CMS). It provides content management, user management, themes and plug-in capabilities to support the creation and management of website content. Its working principle includes database management, template systems and plug-in architecture, suitable for a variety of needs from blogs to corporate websites.

See all articles