Table of Contents
Keyboard events
keyup Event
keypress Event
Example of using keyboard events
Mouse events
Click Event
dbclick 事件
mouseupmousedown 事件
结论
Home Web Front-end JS Tutorial Event Types in JavaScript: Common Keyboard and Mouse Events

Event Types in JavaScript: Common Keyboard and Mouse Events

Sep 03, 2023 am 09:33 AM
mouse events Keyboard events event type

Event Types in JavaScript: Common Keyboard and Mouse Events

JavaScript provides a wide range of events that allow you to interact with and respond to user actions on a web page. Among these events, keyboard and mouse events are the most commonly used. In this article, we'll look at the different types of keyboard and mouse events in JavaScript and see examples of how to use them.

Keyboard events

Keyboard events occur when the user interacts with the keyboard, such as pressing a key, releasing a key, or typing a character. Keyboard events allow us to do some cool things, such as checking if the user entered something correctly into a form, or that something happens when a specific key is pressed. It's as if the website is listening to the keys you press and reacts accordingly. Keyboard events are divided into three types:

<strong>keydown</strong> Event

This keyboard event is triggered when the user presses a key. If the user holds down a key, it will fire repeatedly.

document.addEventListener('keydown', function(event) {
  console.log('Key pressed is:', event.key);
});
Copy after login

This code demonstrates how the keydown event works. It adds an event listener to the document object's keydown event. When a key on the keyboard is pressed, the specified function is performed. This function logs messages to the console. The message contains the string Key Pressed is:, followed by the value of event.key, which represents the key that was pressed.

keyup Event

This keyboard event occurs when the key is released. It can be used to detect when the user releases a specific key.

document.addEventListener('keyup', (event) => {
    var name = event.key;
    alert(`Key pressed: ${name}`);
}, false);
Copy after login

The above code adds an event listener for the keyup event, so that when a key is released on the keyboard, an arrow function will be executed. The arrow function assigns the value of event.key to a variable named name, which represents the released key. When the key is released, an alert box appears with a message containing the string Key Pressed:, followed by the value of the name variable using string interpolation (${ name}).

Another example that can be used to demonstrate the keyup event is to set up an input field and create a function that converts the characters typed in the input field to uppercase when the user releases the key. To try the example below, create an input tag with the id fname and an input tag like onkeyup="myFunction()" < 的函数/strong>Within the input tag.

function myFunction() {
  let x = document.getElementById("fname"); 
  x.value = x.value.toUpperCase();
}
Copy after login

<strong>keypress</strong> Event

The keypress event is triggered when a key is pressed. In the following code example, an event listener is added to the document object that executes a function when a key is pressed and generates a character value. The arrow function logs a message to the browser's console containing the string Key Pressed:, followed by the value of event.key, which represents the character value of the pressed key . p>

document.addEventListener('keypress', (event) => {
    console.log('Key pressed:', event.key);
});
Copy after login
warn Some browsers no longer support the key event, and not all keys (such as Alt, Control, Shift, or Esc) trigger the event in all browsers. It is recommended to use keydown or keyup events instead.

Example of using keyboard events

Mouse events

On the other hand, mouse events can help you create a more attractive website. They handle events that occur when the mouse interacts with an HTML document, such as clicking, moving, or scrolling. They allow us to react when the user clicks a mouse button, moves the mouse over an element, or drags an item on the screen. It's as if the website is tracking your mouse movements and clicks to figure out what you want to do. There are many types of mouse events:

<strong>Click</strong> Event

This event is executed when the user clicks an element.

var element = document.querySelector('.btn');
element.addEventListener('click', function () {
  element.style.backgroundColor = 'blue';
});
Copy after login

To execute the above code, create a button in HTML with the CSS class name btn. The above code uses the querySelector method to select the element with CSS class name btn and assigns it to the element variable. An event listener listening for the click event has been added to the element. When this element is clicked, the specified function will be performed. The function in this example is to change the background color of the element to blue.

您还可以构建一个简单的游戏,用户可以通过使用 math.floormath.random 方法生成随机颜色,在框内单击以连续更改框的背景颜色。

<strong>dbclick</strong> 事件

当用户用鼠标双击某个元素时,此事件调用一个函数。要执行下面的代码示例,请在 HTML 中创建一个 CSS 类名称为 btn 的按钮。使用 querySelector 方法获取元素并向其添加事件侦听器。双击该按钮时,将调用该函数,显示一条警报消息,并且按钮中文本的字体大小会增加。

var button = document.querySelector('.btn');
button.addEventListener('dblclick', function (event) {
  alert('Button double-clicked!');
  button.style.fontSize = '40px';
});
Copy after login

使用 dbclick 事件的高级方法是使用户能够编辑内容。例如,双击文本元素可以将其转换为可编辑的输入字段,允许用户直接进行更改。下面是使用 dbclick 事件编辑内容的演示。

<strong>mouseup</strong><strong>mousedown</strong> 事件

当用户将光标悬停在某个元素上并按下鼠标按钮时,会触发此 mousedown 事件。 创建一个 id 为 text 的按钮。当用鼠标单击该按钮时,会触发消息:“鼠标按钮已按下”。

var button = document.getElementById('text');
button.addEventListener('mousedown', function (event) {
  alert('Mouse button pressed!');
});
Copy after login

用户单击某个元素后释放鼠标按钮时,会触发 mouseup 事件。创建一个 id 为 text 的按钮。当用鼠标单击按钮并释放时,会触发消息:“鼠标按钮已释放”。

var button = document.getElementById('text');
button.addEventListener('mouseup', function (event) {
  alert('Mouse button released!');
});
Copy after login

如何使用这些 mouseupmousedown 事件的实际示例是在实现拖放功能以及绘图和草图时。

<strong>mouseover</strong><strong>mouseout</strong> 事件

当鼠标指针悬停在某个元素上时,会发生 mouseover 事件,而当鼠标指针离开该元素时,会发生 mouseout 事件。这是这两个鼠标事件的快速演示。

在上面的演示中,当用户的鼠标经过图像时,图像会放大,当鼠标离开图像时,图像会恢复到正常大小。

mouseover 事件可用于创建一个工具提示,当鼠标悬停在元素上时,该提示提供有关该元素的附加信息。 mouseovermouseout 事件还可用于创建交互式导航菜单,其中当用户的鼠标指针悬停在菜单项上时会出现子菜单。

<strong>mousemove</strong><strong>mouseleave</strong> 事件

当用户将鼠标光标移动到某个元素上时,会触发 mousemove 事件,当鼠标光标离开该元素时,会触发 mouseleave 事件。这些事件使开发人员能够监视鼠标移动。

每当用户的鼠标位于 div 容器内时,上述代码都会获取鼠标指针坐标,并将坐标显示为框下方的文本。然后,在用户鼠标离开 div 元素后,它会显示文本,指示指针已离开 div。

结论

诸如 keydownkeyupkeypress 之类的键盘事件允许我们捕获并响应来自键盘的用户输入。无论您是实现表单验证、提供键盘快捷键还是创建基于文本的游戏,键盘事件对于用户交互都是至关重要的。另一方面,鼠标事件,如clickdblclickmousedownmouseupmouseovermouseoutmousemovephpcn endcphpcn 和 <code>mouseleave,允许我们捕获并响应用户与鼠标的交互。

In summary, JavaScript's keyboard and mouse events allow us to build websites that appear to be listening and responding to user activity by capturing key presses and mouse movements. Now that you understand the various types of keyboard and mouse events and how to use them to build interactive websites and web applications, go ahead and build fun interactive games and websites. Happy coding!

The above is the detailed content of Event Types in JavaScript: Common Keyboard and Mouse Events. 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 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

Learn to use Vue's v-on directive to handle keyboard shortcut events Learn to use Vue's v-on directive to handle keyboard shortcut events Sep 15, 2023 am 11:01 AM

Learn to use Vue's v-on directive to handle keyboard shortcut events. In Vue, we can use the v-on directive to listen for element events, including mouse events, keyboard events, etc. This article will introduce how to use the v-on directive to handle keyboard shortcut events and provide specific code examples. First, you need to define a method in the Vue instance to handle shortcut key events. For example, we can add a method named handleShortcut to methods: methods:{

Learn to use Vue's v-on instruction to handle mouse move-in and move-out events Learn to use Vue's v-on instruction to handle mouse move-in and move-out events Sep 15, 2023 am 08:34 AM

Learn to use Vue's v-on instruction to handle mouse move-in and move-out events. Mouse move-in and move-out events are one of the common interactive effects in Web pages. Vue provides the v-on instruction to handle these events conveniently. This article will introduce how to use Vue's v-on directive to handle mouse move-in and move-out events, and provide specific code examples. Before using Vue's v-on directive to handle mouse move-in and move-out events, we need to understand the basic usage of the v-on directive. The v-on directive is used to listen to DOM events and

Basic tutorial for learning Pygame: Quick introduction to game development Basic tutorial for learning Pygame: Quick introduction to game development Feb 19, 2024 am 08:51 AM

Pygame installation tutorial: Quickly master the basics of game development, specific code examples are required Introduction: In the field of game development, Pygame is a very popular Python library. It provides developers with rich features and easy-to-use interfaces, allowing them to quickly develop high-quality games. This article will introduce you in detail how to install Pygame and provide some specific code examples to help you quickly master the basics of game development. 1. Installation of Pygame Install Python and start installing Pyga

Event Types in JavaScript: Common Keyboard and Mouse Events Event Types in JavaScript: Common Keyboard and Mouse Events Sep 03, 2023 am 09:33 AM

JavaScript provides a wide range of events that allow you to interact with and respond to user actions on web pages. Among these events, keyboard and mouse events are the most commonly used. In this article, we'll look at the different types of keyboard and mouse events in JavaScript and see examples of how to use them. Keyboard events Keyboard events occur when a user interacts with the keyboard, such as pressing a key, releasing a key, or typing a character. Keyboard events allow us to do some cool things, such as checking if the user entered something correctly into a form, or that something happens when a specific key is pressed. It's as if the website is listening to the keys you press and reacts accordingly. Keyboard events are divided into three types: keydown event

v-on directive in Vue: how to handle mouse events v-on directive in Vue: how to handle mouse events Sep 15, 2023 am 11:39 AM

v-on instruction in Vue: How to handle mouse events, specific code examples are needed. Vue.js is a popular JavaScript framework that uses a componentized approach to build user interfaces. In Vue, you can use the v-on directive to handle various mouse events, such as click, hover, scroll, etc. This article will introduce how to use the v-on directive to handle mouse events and provide specific code examples. In Vue, the v-on directive is used to bind event handlers. Its syntax is v-on: event name, for example

Pygame Installation Guide: An easy-to-understand introductory tutorial Pygame Installation Guide: An easy-to-understand introductory tutorial Feb 20, 2024 pm 12:39 PM

Pygame Installation Tutorial: A simple and easy-to-understand getting started guide, requiring specific code examples Introduction: Pygame is a very popular Python library for developing 2D games. It provides rich functions and easy-to-use interfaces, making game development easier and more interesting. This article will introduce you to the installation process of Pygame and provide specific code examples to help beginners get started quickly. 1. Install Python and Pygame. Download Python and Pygame: First you need to install Python.

How to use Golang to create an efficient game development framework How to use Golang to create an efficient game development framework Mar 06, 2024 pm 06:15 PM

As a popular and efficient programming language in the industry, Golang is also widely used in the field of game development. This article will introduce how to use Golang to create an efficient game development framework and provide specific code examples. We will take a simple 2D game as an example to explain. Part One: Game Engine Construction First, we need to build a simple game engine, including game loop, graphics rendering and other functions. The following is a simple game engine framework: packageenginei

How to solve Vue error: Unable to use v-on correctly to monitor keyboard events How to solve Vue error: Unable to use v-on correctly to monitor keyboard events Aug 17, 2023 pm 10:27 PM

How to solve Vue error: Unable to use v-on to listen to keyboard events correctly. As a popular front-end framework, Vue.js can help us build efficient, flexible and maintainable web applications. Among them, Vue provides the v-on instruction to monitor DOM events to facilitate us to handle user operations. However, when using v-on to monitor keyboard events, we sometimes encounter some errors that prevent us from using this function correctly. This article will walk you through this problem and provide some code examples. Check Vue version

See all articles