嗨,我正在将下面的菜单结构用于响应式网站,在一些帮助下,我设法让子菜单打开和关闭两个子菜单级别上已经打开的任何菜单项。
我正在尝试将 toggleClass('open') 添加到我的脚本中,但我不知道它需要去哪里,以便当通过单击标题打开和关闭菜单项时类切换,并且切换回 .closed当打开另一个菜单项时。通过添加到功能的顶部,我可以在单击标题时切换$(this).toggleClass('open');
它,但如果您打开不同的菜单项,它不会再次切换。
html:
<nav id="main-nav" role="navigation">
<div class="block">
<h2 class="block-title">Main menu</h2>
<ul>
<li class="is-active">
<a href="#">Link</a>
</li><!--
--><li>
<a class="toggle-sub-nav closed" href="#">Link ></a>
<ul class="sub-nav">
<li><a href="#">Sub link</a></li>
<li><a href="#">Sub link</a></li>
<li><a href="#">Sub link</a></li>
</ul>
</li><!--
--><li>
<a href="#">Link</a>
</li><!--
--><li>
<a class="toggle-sub-nav closed" href="#">Link ></a>
<ul class="sub-nav">
<li><a href="#">Sub link</a></li>
<li> <a class="toggle-sub-nav closed" href="#">Sub Link ></a>
<ul class="sub-nav">
<li><a href="#">Sub link</a></li>
<li><a href="#">Sub link</a></li>
<li><a href="#">Sub link</a></li>
</ul></li>
<li><a href="#">Sub link</a></li>
</ul>
</li><!--
--><li>
<a href="#">Link</a>
</li>
</ul>
</div>
</nav>
子菜单CSS:
.sub-nav {
height: 0px;
-webkit-transition: all 600ms cubic-bezier(.42,0,.58,1);
-moz-transition: all 600ms cubic-bezier(.42,0,.58,1);
-o-transition: all 600ms cubic-bezier(.42,0,.58,1);
-ms-transition: all 600ms cubic-bezier(.42,0,.58,1);
transition: all 600ms cubic-bezier(.42,0,.58,1);
overflow:hidden;
}
.sub-nav-open {
height: auto;
max-height: 500px;
}
.sub-nav li { background-color: #666; }
.closed { background: url(../assets/img/arrows.png) no-repeat 90% -24px; }
.open { background: url(../assets/img/arrows.png) no-repeat 90% 17px; }
查询:
$(function () {
$(".toggle-sub-nav").click(function () {
if ($(this).siblings('ul').hasClass('sub-nav-open')) {
$(this).siblings('ul').find('sub-nav-open').andSelf().removeClass('sub-nav-open')
} else {
$('.sub-nav').not($(this).closest('.sub-nav')).removeClass('sub-nav-open');
$(this).next(".sub-nav").toggleClass('sub-nav-open');
}
return false;
});
});