我正在尝试创建一个响应式多级菜单,标记采用以下形式:
<div id="navigation">
<a href="#" id="toggleNav">Menu <i class="fa fa-angle-down"></i></a>
<ul class="nav" id="nav">
<li><a href="/home/" class="">Home</a></li>
<li class="has-subnav"><a href="/shop/" class="active ">Shop</a>
<ul class="">
<li class="nodesktop"><a href="/shop/" class="">Overview</a></li>
<li><a href="/shop/cleanser/" class="">Cleansers</a></li>
<li><a href="/shop/moisturiser/" class="">Moisturisers</a></li>
<li><a href="/shop/treatment/" class="">Serums & Treatments</a></li>
</ul>
</li>
</ul>
</div>
我遇到的问题是,因为我的subnav链接有一个页面url,我使用e.preventDefault来阻止链接被跟踪,并显示我的subnav,然后禁用子链接,所以菜单不起作用。有人有解决方案吗?
$(function () {
var $toggleNav = $('#toggleNav'),
$nav = $('#nav'),
$hasSubnav = $nav.find('> .has-subnav'),
$window = $(window),
windowWidth = $window.width();
$toggleNav.on('click', function (e) {
e.preventDefault();
$nav.toggleClass('visible');
});
$hasSubnav.on('click', function (event) {
event.preventDefault();
$(this).find('ul').toggleClass('show-subnav');
});
});
答案 0 :(得分:0)
好吧,您可能不得不阻止整个<li>
暂停ul
下降的事件,但仅限于<a>
。所以,你的js应该是这样的:
$(function () {
var $toggleNav = $('#toggleNav'),
$nav = $('#nav'),
$hasSubnav = $nav.find('.has-subnav > a'),
$window = $(window),
windowWidth = $window.width();
$toggleNav.on('click', function (e) {
e.preventDefault();
$nav.toggleClass('visible');
});
$hasSubnav.on('click', function (event) {
event.preventDefault();
$(this).parent().find('ul').toggleClass('show-subnav');
});
});