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 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:
keydown
EventThis 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); });
This code demonstrates how thekeydown
event works. It adds an event listener to the document object'skeydown
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 stringKey Pressed is:, followed by the value ofevent.key
, which represents the key that was pressed.
keyup
EventThis 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);
The above code adds an event listener for thekeyup
event, so that when a key is released on the keyboard, an arrow function will be executed. The arrow function assigns the value ofevent.key
to 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 thename
variable using string interpolation (${ name}
).
Another example that can be used to demonstrate thekeyup
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 idfname
and an input tag likeonkeyup="myFunction()"
< 的函数/strong>Within the input tag.
function myFunction() { let x = document.getElementById("fname"); x.value = x.value.toUpperCase(); }
keypress
EventThekeypress
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 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); });
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:
Click
EventThis event is executed whenthe user clicks an element.
var element = document.querySelector('.btn'); element.addEventListener('click', function () { element.style.backgroundColor = 'blue'; });
To execute the above code, create a button in HTML with the CSS class namebtn
. The above code uses thequerySelector
method to select the element with CSS class namebtn
and assigns it to theelement
variable. An event listener listening for theclick
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.floor
和math.random
方法生成随机颜色,在框内单击以连续更改框的背景颜色。
dbclick
事件当用户用鼠标双击某个元素时,此事件调用一个函数。要执行下面的代码示例,请在 HTML 中创建一个 CSS 类名称为btn
的按钮。使用querySelector
方法获取元素并向其添加事件侦听器。双击该按钮时,将调用该函数,显示一条警报消息,并且按钮中文本的字体大小会增加。
var button = document.querySelector('.btn'); button.addEventListener('dblclick', function (event) { alert('Button double-clicked!'); button.style.fontSize = '40px'; });
使用dbclick
事件的高级方法是使用户能够编辑内容。例如,双击文本元素可以将其转换为可编辑的输入字段,允许用户直接进行更改。下面是使用dbclick
事件编辑内容的演示。
mouseup
和mousedown
事件当用户将光标悬停在某个元素上并按下鼠标按钮时,会触发此mousedown
事件。创建一个 id 为text
的按钮。当用鼠标单击该按钮时,会触发消息:“鼠标按钮已按下”。
var button = document.getElementById('text'); button.addEventListener('mousedown', function (event) { alert('Mouse button pressed!'); });
当用户单击某个元素后释放鼠标按钮时,会触发mouseup
事件。创建一个 id 为text
的按钮。当用鼠标单击按钮并释放时,会触发消息:“鼠标按钮已释放”。
var button = document.getElementById('text'); button.addEventListener('mouseup', function (event) { alert('Mouse button released!'); });
如何使用这些mouseup
和mousedown
事件的实际示例是在实现拖放功能以及绘图和草图时。
mouseover
和mouseout
事件当鼠标指针悬停在某个元素上时,会发生mouseover
事件,而当鼠标指针离开该元素时,会发生mouseout
事件。这是这两个鼠标事件的快速演示。
在上面的演示中,当用户的鼠标经过图像时,图像会放大,当鼠标离开图像时,图像会恢复到正常大小。
mouseover
事件可用于创建一个工具提示,当鼠标悬停在元素上时,该提示提供有关该元素的附加信息。mouseover
和mouseout
事件还可用于创建交互式导航菜单,其中当用户的鼠标指针悬停在菜单项上时会出现子菜单。
mousemove
和mouseleave
事件当用户将鼠标光标移动到某个元素上时,会触发mousemove
事件,当鼠标光标离开该元素时,会触发mouseleave
事件。这些事件使开发人员能够监视鼠标移动。
每当用户的鼠标位于div
容器内时,上述代码都会获取鼠标指针坐标,并将坐标显示为框下方的文本。然后,在用户鼠标离开div
元素后,它会显示文本,指示指针已离开 div。
诸如keydown
、keyup
和keypress
之类的键盘事件允许我们捕获并响应来自键盘的用户输入。无论您是实现表单验证、提供键盘快捷键还是创建基于文本的游戏,键盘事件对于用户交互都是至关重要的。另一方面,鼠标事件,如click
、dblclick
、mousedown
、mouseup
、mouseover
、mouseout
、mousemovephpcn 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!