Home >Web Front-end >Front-end Q&A >How to implement JavaScript hover function in HTML

How to implement JavaScript hover function in HTML

PHPz
PHPzOriginal
2023-04-25 10:46:411789browse

JavaScript hover function means that when the mouse pointer hovers over an element, you can perform specified operations, such as displaying prompt information, changing element styles, etc. This feature is very common in web design and can provide users with a better interactive experience. To implement JavaScript hover functionality in HTML, you can follow the steps below.

Step one: Write HTML code

First, you need to write basic HTML code, including the elements that need to implement the hover function. For example, we can create a simple div element as shown below:

<div id="myDiv">这是一个 div 元素</div>

Step 2: Add JavaScript code

Next, you need to add JavaScript code to implement the hover function. You can place the JavaScript code in the head element of the HTML file, or you can place it in an external .js file and then reference it. For example, the following is a simple JavaScript code:

const myDiv = document.getElementById("myDiv");
myDiv.addEventListener("mouseover", function() {
  myDiv.style.backgroundColor = "red";
});

myDiv.addEventListener("mouseout", function() {
  myDiv.style.backgroundColor = "white";
});

This code first obtains the element with the id "myDiv" through the document.getElementById("myDiv") method. Then, add two event listeners to the element through the addEventListener() method. The first listener is mouseover, which represents an event that is triggered when the mouse pointer hovers over the element. When the event is triggered, we can set the background color of the element to red through the style.backgroundColor method. The second listener is mouseout, which represents the event triggered when the mouse pointer leaves the element. When the event fires, we can reset the background color to white.

The effect of this code is that when the mouse pointer hovers over the div element, its background color turns red, and when the mouse pointer leaves, the background color returns to white.

Step 3: Call the JavaScript code

Finally, you need to connect the JavaScript code to the HTML page to make the hover function take effect. JavaScript code can be called by:

  • Place JavaScript code directly within the