开发者

Auto applying 'height' data to submenu's with jQuery

开发者 https://www.devze.com 2022-12-10 07:22 出处:网络
I have a fairly simple menu structure, one level deep, made using UL/LI\'s as below... Menu Item 1 Menu Item 2

I have a fairly simple menu structure, one level deep, made using UL/LI's as below...

  • Menu Item 1
  • Menu Item 2
  • Menu Item 3
    • Sub Item 1
    • Sub Item 2
    • Sub Item 3
  • Menu Item 4

The menus are displayed in a vertical fashion with a roll-out on hover, in exactly the same basic format as the vertical suckerfish demos shown here: http://htmldog.com/articles/suckerfish/dropdowns/example/vertical.html

What I want to do is, using jQuery, automatically apply a class to the LI of each sub menu with the corresponding height of the menu item. For example Sub Item 1 is beside Menu Item 3, which would make it's 'height' 3. Sub Item 2 has a 'height' of 4. Sub Menu 2 of Menu Item 4 would have a 'height' of 5. etc.

The reason I am doing this is the sub-menu items need to have a css style which will fit in with the background - the menu is curved - so they need to have a class applied so the styling will be correct for their height.

I am fairly sure the code required shouldn't be too large - it just needs to add a class of the style 'height1' or 'height2' etc. to each sub li, I just can't think where to start myself as my javascript skills are still开发者_开发百科 a bit rudimentary!

Thanks in advance!


Something like this should do the trick. Just swap out #nav with the id of your UL. Also, this assumes a zero-indexed height (height0, height1, height2, etc.).

function applyHeightClasses( el, offset ){
  if(! ( offset > 0 ) ) offset = 0;

  $( el ).children( 'li' ).each( function( i ) {
    $(this).addClass( 'height' + ( offset + i ) );

    $(this).children( 'ul' ).each( function( x ) {
      applyHeightClasses( this, ( offset + i + x ) );
    });

  });
}

$(document).ready(function() {
  applyHeightClasses('#nav');
});
0

精彩评论

暂无评论...
验证码 换一张
取 消