jQuery toggle menu hide/show (close other menus when new menu opens)

偶尔善良 提交于 2019-12-09 13:55:05

问题


thanks to Nick Craver I've got a nice toggle menu going, however i've come up with the problem that if users keep clicking new menus the page will keep growing which i dont want, so the idea is:

as one menu opens, any currently open menus to close.

The full source is @ http://the-dot.co.uk/new/

here are 2 snippets of the code I'm using.

<script type="text/javascript">
$(document).ready(function() {
$("ul li a").click(function() { $(this).parent().next().toggle("fast"); });
});
</script>

and html structure is

 <ul class="navigation">
    <li><a name="us" title="us">Us</a></li>
    <li id="us">about thedot</li>
    <li><a name="portfolio" title="portfolio">Portfolio</a></li>
    <li></li>
    <li><a name="contact" title="contact">Contact</a></li>
    <li id="contact">contact deets
    </li>
    <li><a name="twitter" title="twitter">Twitter</a></li>
    <li id="twit">some twitter shit</li>
    <li><a href="#">Blog</a></li>
  </ul>

thanks.


回答1:


You can do something like this:

$(function() {
  $("ul li a").click(function() { 
      $(this).parent().next().toggle("fast").siblings("[id]").hide("fast");
  });
});

You can test it out here, what this does it toggle the sibling <li> still, but then looks at its .siblings() that have an ID attribute and .hide() them if show.


If the markup isn't locked in, you could simplify it further like this:

<ul class="navigation">
    <li class="toggle">Us</li>
    <li class="content">about thedot</li>
    <li class="toggle">Portfolio</li>
    <li class="content"></li>
    <li class="toggle">Contact</li>
    <li class="content">contact deets</li>
    <li class="toggle">Twitter</li>
    <li class="content">some twitter shit</li>
    <li><a href="#">Blog</a></li>
</ul>

And script like this:

$(function() {
  $("li.content").hide();
  $("ul.navigation").delegate("li.toggle", "click", function() { 
      $(this).next().toggle("fast").siblings(".content").hide("fast");
  });
});

It's a matter of preference, but I find this approach a bit cleaner and more style-able, check out the result here.



来源:https://stackoverflow.com/questions/4319809/jquery-toggle-menu-hide-show-close-other-menus-when-new-menu-opens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!