<div id="topMenu"> <div id="activeMenu" style="left: -999px; width: 0px;"></div> <ul> <li><a href="#" class="mainlevel" id="active_menu"> 1</a></li> <li><a href="#" class="mainlevel"> 2</a></li> <li><a href="#" class="mainlevel"> 3</a></li> <li><a href="#" class="mainlevel lastMenuItem"> 4</a></li> </ul> </div>​
#topMenu{ clear: both; position: relative; overflow: hidden; top: 23px; margin-left: 14px; } #topMenu a{ font-family: Arial; font-size: 12px; font-weight: bold; text-transform: uppercase; color: #686868; text-decoration: none; display: block; float: left; height: 32px; vertical-align: middle; padding-top: 14px; padding-left: 20px; padding-right: 20px; border-left: 1px solid #ccc; z-index: 2; position: relative; } #topMenu a:hover{ text-decoration: none; color: #3d3d3d; } #topMenu a.lastMenuItem{ border-right: 1px solid #ccc; } #activeMenu{ position: absolute; width: 0px; height: 47px; left: -999px; background: #c0c0c0; z-index: 1; }
jQuery(document).ready(function(){ if(jQuery("#active_menu").length>0){ // , var menuWidth = jQuery("#active_menu").outerWidth(); // var menuLeft = jQuery("#active_menu").position().left; // jQuery("#activeMenu").stop().animate({ // left: menuLeft+'px', width: menuWidth+'px' }, 500, 'linear'); } jQuery("#topMenu a.mainlevel").mouseover(function(){ // . , , , var menuWidth = jQuery(this).outerWidth(); var menuLeft = jQuery(this).position().left; jQuery("#activeMenu").stop().animate({ left: menuLeft+'px', width: menuWidth+'px' }, 300, 'linear'); }); jQuery("#topMenu").mouseleave(function(){ // ( , ) if(jQuery("#active_menu").length<=0){ // , jQuery("#activeMenu").stop().animate({ left: '-999px', width: '0px' }, 500, 'linear'); } else{ // , – var menuWidth = jQuery("#active_menu").outerWidth(); var menuLeft = jQuery("#active_menu").position().left; jQuery("#activeMenu").stop().animate({ left: menuLeft+'px', width: menuWidth+'px' }, 500, 'linear'); } }); });​
And about constructive criticism:
1. The animation you have at different events is the same, so you should write only one function and call it when necessary.
2. You constantly refer to the same elements and you are constantly searching for DOM - this is wrong. These elements should be cached in variables.
3. Well, read about the event .on ()
jsfiddle.net/bYY6Y/71/
Source: https://habr.com/ru/post/159563/
All Articles