开发者

jQuery open and close nested ul nav depending on location

I'm making a sub nav in wordpress and have a nested list style menu. An example of the HTML is below. Whichever is the current item has the li class "current_page_item". I need all child menus collapsed unless there is a current_page_item class on the parent or one of t开发者_如何转开发he children.

<ul>
 <li class="current_page_item"><a href="#">Parent Item</a>
  <ul class="children">
   <li><a href="#">Child page</a></li>
   <li><a href="#">Child page</a></li>
   <li><a href="#">Child page</a></li>
   <li><a href="#">Child page</a></li>
  </ul>
 </li>
 <li><a href="#">Parent Item</a>
  <ul class="children">
   <li><a href="#">Child page</a></li>
   <li><a href="#">Child page</a></li>
  </ul>
 </li>
 <li><a href="#">Parent Item</a>
  <ul class="children">
   <li><a href="#">Child page</a></li>
   <li><a href="#">Child page</a></li>
  </ul>
 </li>
 <li><a href="#">Parent Item</a></li>
 <li><a href="#">Parent Item</a></li>
</ul>

This so far, which works but i wonder if it can be improved as there is some flashing open and then closed again....

jQuery('ul.children').slideUp();
jQuery('li.current_page_item ul.children').slideDown('medium');
jQuery('li.current_page_item').parent().slideDown('medium');


If you want stuff to slide up or down, but not both, use something like this:

// In one line:
jQuery('ul.children').not(jQuery('ul.children:has(li.current_page_item), li.current_page_item ul.children').slideDown()).slideUp();

// In three more readable lines:
var $active = jQuery('ul.children:has(li.current_page_item), li.current_page_item ul.children');
jQuery('ul.children').not($active).slideUp();
$active.slideDown();

Or, if you want everything to start out hidden and then slide down the active elements, use this:

jQuery('ul.children').hide();
jQuery('ul.children:has(li.current_page_item), li.current_page_item ul.children').slideDown();

Of course, you can also use $ instead of jQuery, but I'll stick to your style.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜