JQuery's hover event is only for a single HTML element. However, sometimes we want to trigger fun1 when the mouse enters two or more elements and trigger fun2 when they leave, moving the mouse between these elements does not trigger any event.
1. Requirements
The hover event of jQuery only targets a single HTML element, for example:
The Code is as follows:
$ ('# Login'). hover (fun2, fun2 );
When you move to the # login element, call the fun1 function. When you leave, call the fun2 function. This API can meet most of the requirements.
However, sometimes we want to trigger fun1 when the mouse moves into two or more elements and trigger fun2 when they leave, and moving the mouse between these elements does not trigger any events. For example:
Trigger fun1 when the mouse enters the two areas, and trigger fun2 when the mouse leaves. You may want to use the following method:
The Code is as follows:
$ ('# Trigger, # drop'), hover (fun1, fun2 );
This method does not meet our needs, because the entry from # trigger to # drop triggers fun2 and fun1. To solve this problem, a simple method is to change the HTML structure. The implementation method is as follows:
The Code is as follows:
$ ('# Iner'). hover (fun1, fun2 );
In this way, the hover event is bound to the parent element to implement this function.
2. Example Study
A simplified image is a common drop-down menu. The HTML structure is as follows:
The Code is as follows:
Ul id = "# nav">
Drop-down menu
- Drop-down Item 1
- Drop-down Item 2
- Drop-down Item 3
The implementation of the JavaScrip program is also very simple
The Code is as follows:
$ ('# Droplist'). hover (function (){
$ (This). find ('ul '). show ();
}, Function (){
$ (This). find ('ul '). hide ();
});
This implementation method is logically clear, but leads to too many HTML nested hierarchies, causing a lot of inconvenience when writing CSS. For example:
The Code is as follows:
# Nav li {font-size: 14px ;}
We want this CSS to set a 14-pixel font for the first li element, but it also applies to the second element, so we have to use the following statement to rewrite it.
The Code is as follows:
# Nav li {font-size: 12px ;}
3. Solution
Change HTML Structure
The Code is as follows:
- Drop-down Item 1
- Drop-down Item 2
- Drop-down Item 3
Introduce JS files in sequence
The Code is as follows: