1. Introduction to requirements jQuery’s hover event is only for a single HTML element, for example:
$('#login').hover(fun2, fun2);
The fun1 function is called when the mouse enters the #login element , the fun2 function is called when leaving. This API can meet most needs.
However, sometimes we want fun1 to be triggered when the mouse enters two or more elements, and fun2 to be triggered when the mouse leaves them, while moving the mouse between these elements does not trigger any events. For example, two HTML elements are next to each other, as shown below:
Fun1 is triggered when the mouse enters the area between the two, and fun2 is triggered when the mouse leaves. You may think of using the following method
$('# trigger, #drop'),hover(fun1, fun2);
This method does not meet our needs, because fun2 and fun1 will be triggered when entering #drop from #trigger. To solve this problem, a relatively simple way is to change the HTML structure. The implementation is as follows:
< ;/div>
$('#container').hover(fun1, fun2);
This way by binding on the parent element hover event to achieve this function.
2. Example study The picture below is a simplified diagram of a common drop-down menu. The HTML structure is as follows:
ul id="#nav">
< ;/li>
Drop-down menu
- Dropdown item 1
- Dropdown item 2
- Dropdown item 3
The implemented JavaScript program is also very simple
$('#droplist').hover(function(){
$( this).find('ul').show();
}, function(){
$(this).find('ul').hide();
});
This implementation method has clear logic, but it results in too many nested levels of HTML and a lot of inconvenience when writing CSS. For example:
#nav li { font-size:14px; }
We want this CSS to set a 14-pixel font for the first-layer li element, but it also affects the second-layer element, so we have to use the following statement to rewrite it
#nav li li { font-size:12px; }
3. Solution Change HTML structure
- Dropdown item 1
- Dropdown item 2
- Dropdown item 3
Introduce JS files in sequence
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31