Home >Web Front-end >JS Tutorial >Detailed explanation of the usage of mouseover events in JavaScript
The mouseover event is an event triggered when the mouse cursor overlaps with the element represented by its name. In this article, we will introduce the usage of mouseover events in JavaScript in detail.
Let’s take a look firstWhat is onmouseover?
The mouseover activity is the "event", and onmouseover is the event handler.
Event handlers are required to specify the process to be executed when an event occurs.
So onmouseover is an event handler that is responsible for processing when the mouse cursor hovers over an element.
What is onmouseleave?
In addition to onmouseover, there is also onmouseleave.
As the name suggests, it handles events that are triggered when the mouse cursor leaves an element.
These two attributes will be used in the following example. Let's look at the usage code of the mouse hover event.
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> </head> <body> <div id="div1" style="width: 150px; height: 150px; padding: 10px; background-color:pink; border: 1px solid #000000" onmouseover="over(this)" onmouseleave="leave(this)"></div> </body> <script> function over(x) { x.style.backgroundColor = "blue"; } function leave(x) { x.style.backgroundColor = "red"; } </script> </html>
In the above code, we first create a simple using the div tag of square.
The background color of the block is specified as light pink.
Then, we register the event handler using the HTML event attribute.
As shown in the code, the onmouseover attribute and onmouseleave attribute have been added to the code of the div tag.
The onmouseover attribute specifies the over function that is activated when the mouse cursor is on the block.
onmouseover="over(this)"
In the parameters of the over function, this indicates that the div element itself is the parameter of the over function.
Theover function accesses the style.backgroundColor property of the div element and sets the background color of the square to blue.
Specify the leave function for the onmouseleave attribute.
Like the over function, the leave function can also access the style.backgroundColor property of the div element and set the square background color to red.
By doing this, the originally pink square turns blue when the cursor is placed over the square, and turns red when moved away from the square.
The above is the detailed content of Detailed explanation of the usage of mouseover events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!