我正在WordPress中构建一个单击下拉菜单。一切正常,但我对一个功能感到困惑。通过切换"显示"下拉菜单会在点击时展开和折叠。类。如果单击另一个父导航项,我还需要添加隐藏扩展下拉列表的功能。这样,2次下降将永远不会同时打开。代码如下,谢谢。
HTML
<ul id="primary-nav">
<li class="menu-item-has-children">Parent Nav Item One
<!-- if Parent Nav Item Two is clicked and this sub-menu is visible, hide this sub-menu -->
<ul class="sub-menu">
<li class="menu-item-has-children">Drop Down Item
<ul class="sub-menu">
<li>Drop Down Sub Item</li>
<li>Drop Down Sub Item</li>
</ul>
</li>
<li>Drop Down Item</li>
</ul>
<li class="menu-item-has-children">Parent Nav Item Two
<!-- if Parent Nav Item One is clicked and this sub-menu is visible, hide this sub-menu -->
<ul class="sub-menu">
<li>Drop Down Item</li>
<li>Drop Down Item</li>
</ul>
</li>
</ul>
JS
$('#primary-nav .menu-item-has-children').click(function() {
$('> .sub-menu', this).toggleClass('show');
});
答案 0 :(得分:2)
首先隐藏它们,同时保持点击状态,以便切换它:
$('#primary-nav .menu-item-has-children').click(function() {
var state = $('> .sub-menu', this).hasClass('show');
$('#primary-nav .menu-item-has-children .sub-menu').removeClass('show');
$('> .sub-menu', this).toggleClass('show', !state);
});
.sub-menu {display: none}
.sub-menu.show {display: block}
.menu-item-has-children {cursor: pointer}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="primary-nav">
<li class="menu-item-has-children">Parent Nav Item One
<!-- if Parent Nav Item Two is clicked and this sub-menu is visible, hide this sub-menu -->
<ul class="sub-menu">
<li class="menu-item-has-children">Drop Down Item
<ul class="sub-menu">
<li>Drop Down Sub Item</li>
<li>Drop Down Sub Item</li>
</ul>
</li>
<li>Drop Down Item</li>
</ul>
<li class="menu-item-has-children">Parent Nav Item Two
<!-- if Parent Nav Item One is clicked and this sub-menu is visible, hide this sub-menu -->
<ul class="sub-menu">
<li>Drop Down Item</li>
<li>Drop Down Item</li>
</ul>
</li>
</ul>