Home > Web Front-end > JS Tutorial > body text

Event Types in JavaScript: Common Keyboard and Mouse Events

WBOY
Release: 2023-09-03 09:33:10
Original
975 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template