Jquery:手风琴菜单slideDown和slideUp

时间:2013-05-30 02:45:12

标签: jquery css accordion

我有这段代码:

<ul class="main">
    <li><a href="#">main menu1<span class="open"> </span></a>
            <ul class="submenu">
                <li><a href="#">submenu1</a></li>
                <li><a href="#">submenu2</a></li>
                <li><a href="#">submenu3</a></li>
                <li><a href="#">submenu4</a></li>
                <li><a href="#">submenu5</a></li>
            </ul>
       </li>
    <li><a href="#">main menu2<span class="open">  </span></a>
            <ul class="submenu">
                <li><a href="#">submenu1</a></li>
                <li><a href="#">submenu2</a></li>
                <li><a href="#">submenu3</a></li>
                <li><a href="#">submenu4</a></li>
                <li><a href="#">submenu5</a></li>
            </ul>
      </li>
</ul>

和手风琴菜单的这个jquery

     var submenu = $('.submenu').hide();

  $('.open').click(function() {
      $this = $(this);
      $target =  $this.parent().next();

      if(!$this.hasClass('close')){
         $('.open').removeClass('close');
         submenu.slideUp();
         $this.addClass('close');
         $target.slideDown();
      }
  });

就像这样,单击右侧的按钮,其submenu向下滑动,其他的则向上滑动。

我想要点击它本身(我的意思是右边的按钮,当前哪个子菜单是打开的),它的submenu也会向上滑动。

我该怎么做?

Here is the code in jsFiddle

1 个答案:

答案 0 :(得分:1)

非常简单,使用else条件并只使用$target.slideUp();

if(!$this.hasClass('close')){
     $('.open').removeClass('close');
     submenu.slideUp();
     $this.addClass('close');
     $target.slideDown();
}else{
     $target.slideUp();
     $this.removeClass('close');
}

Here's your fiddle