如何在单击事件上单击下一个子菜单时关闭先前打开的子菜单

时间:2017-02-25 12:26:23

标签: javascript jquery html5 css3 menu

我有一个带子菜单的菜单。我必须在点击时打开一个下拉菜单,然后在点击其他菜单时再次关闭。如果我点击菜单,我的下面的代码都显示下拉列表。我必须一次只显示一个下拉菜单。你能帮帮我吗?

注意在第二个li代码中我使用div代码

$('.sub-menu').hide();
   $("li:has(ul)").click(function(){
     $("ul",this).slideDown();
  });
.menu ul.nav-menu{
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="menu">
<ul class="nav-menu">
	
<li class="main-list"><a href="#">home</a>

	<ul class="sub-menu">
		<li><a href="#">home1</a></li>
		<li><a href="#">home2</a></li>
	</ul>
</li>

<li class="main-list"><a href="#">service</a>
  <div class="square">
	 <div class="sub">
		<ul class="sub-menu">
			<li><a href="#">home1</a></li>
			<li><a href="#">home2</a></li>
		</ul>
	  </div>
	</div>
</li>

</ul>
</div>

3 个答案:

答案 0 :(得分:2)

使用slideUp()slideDown(),如下所示: -

$('.sub-menu').hide();
$("li:has(ul)").click(function(){
  $(".main-list").find('.sub-menu').slideUp();
  $(this).find('.sub-menu').slideDown();
});
.menu ul.nav-menu{
	list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="menu">
   <ul class="nav-menu">
      <li class="main-list"><a href="#">home</a>
        <ul class="sub-menu">
          <li><a href="#">home1</a></li>
          <li><a href="#">home2</a></li>
        </ul>
      </li>
      <li class="main-list"><a href="#">service</a>
          <div class="square">
            <div class="sub">
              <ul class="sub-menu">
                  <li><a href="#">home1</a></li>
                  <li><a href="#">home2</a></li>
              </ul>
            </div>
        </div>
      </li>
    </ul>
</div>

答案 1 :(得分:1)

根据点击的元素,它会显示相应的子菜单。

$('.sub-menu').hide();
$(".main-list").click(function() {
  $(".main-list").find('.sub-menu').hide();
  $(this).find('.sub-menu').fadeIn();
});
.menu ul.nav-menu {
  list-style: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="menu">
  <ul class="nav-menu">

    <li class="main-list"><a href="#">home</a>

      <ul class="sub-menu">
        <li><a href="#">home1</a></li>
        <li><a href="#">home2</a></li>
      </ul>
    </li>

    <li class="main-list"><a href="#">service</a>
      <div class="square">
        <div class="sub">
          <ul class="sub-menu">
            <li><a href="#">home1</a></li>
            <li><a href="#">home2</a></li>
          </ul>
        </div>
      </div>
    </li>

  </ul>
</div>

答案 2 :(得分:1)

跟踪变量中最后打开的子菜单,并在打开另一个菜单时将其关闭:

var lastOpen = null;
$('.sub-menu').hide();
$("li:has(ul)").click(function(){
    if (lastOpen != null){
         lastOpen.hide();
         lastOpen = null;
    }
    lastOpen = $("ul",this).slideDown();
});