Event Types in JavaScript: Common Keyboard and Mouse Events

WBOY
Release: 2023-09-03 09:33:10
Original
906 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:

keydownEvent

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 thekeydownevent works. It adds an event listener to the document object'skeydownevent. When a key on the keyboard is pressed, the specified function is performed. This function logs messages to the console. The message contains the stringKey Pressed is:, followed by the value ofevent.key, which represents the key that was pressed.

keyupEvent

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 thekeyupevent, so that when a key is released on the keyboard, an arrow function will be executed. The arrow function assigns the value ofevent.keyto a variable namedname, which represents the released key. When the key is released, an alert box appears with a message containing the stringKey Pressed:, followed by the value of thenamevariable using string interpolation (${ name}).

Another example that can be used to demonstrate thekeyupevent 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 idfnameand an input tag likeonkeyup="myFunction()"< 的函数/strong>Within the input tag.

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

keypressEvent

Thekeypressevent 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 stringKey Pressed:, followed by the value ofevent.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. Theyhandle eventsthat 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:

ClickEvent

This event is executed whenthe 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 namebtn. The above code uses thequerySelectormethod to select the element with CSS class namebtnand assigns it to theelementvariable. An event listener listening for theclickevent 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方法生成随机颜色,在框内单击以连续更改框的背景颜色。

dbclick事件

当用户用鼠标双击某个元素时,此事件调用一个函数。要执行下面的代码示例,请在 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事件编辑内容的演示。

mouseupmousedown事件

当用户将光标悬停在某个元素上并按下鼠标按钮时,会触发此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事件的实际示例是在实现拖放功能以及绘图和草图时。

mouseovermouseout事件

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

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

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

mousemovemouseleave事件

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

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

结论

诸如keydownkeyupkeypress之类的键盘事件允许我们捕获并响应来自键盘的用户输入。无论您是实现表单验证、提供键盘快捷键还是创建基于文本的游戏,键盘事件对于用户交互都是至关重要的。另一方面,鼠标事件,如clickdblclickmousedownmouseupmouseovermouseoutmousemovephpcn endcphpcn 和 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!