jQuery toggle menu hide/show (close other menus wh

2020-06-28 22:02发布

问题:

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.