jQuery 切换菜单隐藏/显示(当新菜单打开时关闭其他菜单)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4319809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:04:12  来源:igfitidea点击:

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

jquerymenutoggleshow-hide

提问by Owen

thanks to Nick CraverI'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:

感谢Nick Craver我有一个很好的切换菜单,但是我想出了一个问题,如果用户不断点击新菜单,页面将继续增长,这是我不想要的,所以我的想法是:

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

当一个菜单打开时,任何当前打开的菜单将关闭。

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

完整来源是@ http://the-dot.co.uk/new/

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

这是我正在使用的代码的 2 个片段。

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

and html structure is

和html结构是

 <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.

谢谢。

回答by Nick Craver

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.

您可以在此处对其进行测试,它<li>仍然会切换同级,但随后查看.siblings()具有 ID 属性的属性,.hide()如果显示,则查看它们。



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.

这是一个偏好问题,但我发现这种方法更简洁、更时尚,请在此处查看结果