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:
-
key
: This property returns a string representing the character value of the key pressed. -
code
: This property returns a string representing the code of the physical key pressed. -
repeat
: If a key is pressed for a long time, this property will return a Boolean valuetrue
, causing thekeydown
event to be triggered multiple times. -
altKey
: If the user presses the Alt key (on Windows) or the Option key (on macOS) whenWhen the keydown
event is triggered. -
ctrlKey
: If the user presses theControl
key when the keydown event fires, this property returns a Boolean valuetrue
. -
metaKey
: If the user presses theMeta
key when the keydown event fires, this property returns a Boolean valuetrue
. -
shiftKey
: If the user presses theShift
key when the keydown event fires, this property returns a Boolean valuetrue
.
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
屬性的值將變?yōu)?3 > 并且 code
屬性的值變?yōu)?Digit3。但是,按下 Shift 后,key
屬性的值將變?yōu)?#,而 code
屬性仍為 Digit3。
您可以嘗試使用其他組合鍵進(jìn)行相同的操作,您會注意到 key
屬性的值會根據(jù)您按下的鍵而變化。但是,code
屬性的值保持不變。
鍵盤上的某些鍵通常是重復(fù)的。例如,有兩個 Shift 鍵。按左鍵會將 code
的值設(shè)置為 ShiftLeft
。按右邊會將 code
的值設(shè)置為 ShiftRight
。同樣,有兩組數(shù)字鍵。字母上方的代碼將為您提供 Digit<Number>
代碼,而數(shù)字鍵盤上的代碼將為您提供 Numpad<Number>
代碼。
這意味著,如果您的代碼依賴于檢測特定鍵,則務(wù)必確保您使用 code
屬性來檢查按下了哪個鍵。
我想提的另一件重要的事情是,并不是每個人都使用 QWERTY 鍵盤,而且他們的鍵盤甚至可能不是英文的。在這種情況下,使用 key
屬性來檢查按下了哪個鍵很容易出錯。
響應(yīng)鍵盤事件
現(xiàn)在我們知道了如何監(jiān)聽鍵盤事件并從中提取信息,我們可以編寫一些代碼來對某些特定鍵的 keydown
和 keyup
事件做出反應(yīng)??紤]以下代碼片段:
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); } });
我們?yōu)?keydown
事件創(chuàng)建了一個偵聽器,并為 keyup
事件創(chuàng)建了另一個偵聽器。這兩個事件都附加到 document
。
在 keydown
內(nèi),我們檢查三個不同的密鑰。我使用了 R 鍵的 event.code
屬性來向您展示您可以單獨(dú)按 R 鍵或與任何修飾鍵組合使用,并且它仍會將圓的半徑更改為隨機(jī)值。另一方面,我們使用 event.key
屬性來檢查其值是否為 B。僅當(dāng)您同時按 Shift 和 B 時,此塊中的代碼才會執(zhí)行??,因?yàn)檫@種組合會導(dǎo)致 event.key
屬性成為大寫“B”。
在 keyup
內(nèi),我們檢查 ArrowUp
鍵上的 keyup
事件。一旦鑰匙被解除,我們會在四秒的延遲后刪除之前附加的類。
以下 CodePen 演示展示了這一切的實(shí)際效果:
您應(yīng)該嘗試在上述代碼中添加自己的邏輯,以便當(dāng)用戶按下A、S、W鍵時圓圈會移動> 和D。
最終想法
在本教程中,我們學(xué)習(xí)了 JavaScript 中鍵盤事件的基礎(chǔ)知識。按下并釋放鍵盤上的按鍵將分別觸發(fā) keydown
和 keyup
事件。與這些事件關(guān)聯(lián)的 event
對象包含您確定按下了哪個鍵并采取適當(dāng)操作所需的所有信息。
請記住,鍵盤只是眾多可能的輸入設(shè)備之一。因此,使用鍵盤檢測任何輸入可能并不總是能達(dá)到預(yù)期效果。在這種情況下,您應(yīng)該考慮使用與輸入相關(guān)的事件。
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To roll back the WordPress version, you can use the plug-in or manually replace the core file and disable automatic updates. 1. Use WPDowngrade and other plug-ins to enter the target version number to automatically download and replace; 2. Manually download the old version of WordPress and replace wp-includes, wp-admin and other files through FTP, but retain wp-config.php and wp-content; 3. Add code in wp-config.php or use filters to disable core automatic updates to prevent further upgrades. Be sure to back up the website and database before operation to ensure safety and reliability. It is recommended to keep the latest version for security and functional support in the long term.

The steps to create a custom shortcode in WordPress are as follows: 1. Write a PHP function through functions.php file or custom plug-in; 2. Use add_shortcode() to bind the function to the shortcode tag; 3. Process parameters in the function and return the output content. For example, when creating button shortcodes, you can define color and link parameters for flexible configuration. When using it, you can insert a tag like [buttoncolor="red"url="https://example.com"] in the editor, and you can use do_shortcode() to model it

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

Object cache assists persistent storage, suitable for high access and low updates, tolerating short-term lost data. 1. Data suitable for "persistence" in cache includes user configuration, popular product information, etc., which can be restored from the database but can be accelerated by using cache. 2. Select a cache backend that supports persistence such as Redis, enable RDB or AOF mode, and configure a reasonable expiration policy, but it cannot replace the main database. 3. Set long TTL or never expired keys, adopt clear key name structure such as user:1001:profile, and update the cache synchronously when modifying data. 4. It can combine local and distributed caches to store small data locally and big data Redis to store big data and use it for recovery after restart, while paying attention to consistency and resource usage issues.

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.
