我用子菜单制作了这个简单的响应式菜单。但是当我在手机上点击“触发器”时它没有第一次打开,我必须再次点击它。然后,当我想向下滚动菜单时,它会关闭。
HTML:`
<a href="" class="mobile-trigger">Nav Trigger<span aria-hidden="true"></span></a>
<div class="nav-main__inner">
<nav class="nav-main__top cf">
<ul class="nav-main__left">
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--bold" href="">Link</a></li>
</ul>
<ul class="nav-main__right">
<li class="nav-main__item"><a class="item__link item__link--medium" href="">Link</a></li>
<li class="nav-main__item"><a class="item__link item__link--medium" href="">Link</a></li>
<li class="nav-main__item has-submenu"><a class="item__link item__link--medium" href="">Link</a>
<ul class="submenu">
<li class="submenu__item"><a href="" class="submenu__link">Link sub</a></li>
<li class="submenu__item"><a href="" class="submenu__link">Link sub</a></li>
<li class="submenu__item"><a href="" class="submenu__link">Link sub</a></li>
<li class="submenu__item"><a href="" class="submenu__link">Link sub</a></li>
<li class="submenu__item"><a href="" class="submenu__link">Link sub</a></li>
<li class="submenu__item"><a href="" class="submenu__link">Link sub</a></li>
</ul>
</li>
</ul>
</nav>`
Javascript:
$(document).ready(function(){
var trigger = $('.mobile-trigger');
var subm = $('.submenu');
var navInner = $('.nav-main__inner');
function mmenu(){
var wi = $(window).width();
if(wi < 992) {
trigger.on('click', function(e){
e.preventDefault();
trigger.toggleClass('nav-open');
navInner.toggleClass('show');
if (subm.hasClass('show')) {
subm.removeClass('show');
}
});
$('.has-submenu > a').on('click', function(e){
e.preventDefault();
subm.toggleClass('show');
});
}
$(window).resize(function(){
navInner.removeClass('show');
trigger.removeClass('nav-open');
});
}
mmenu();
});`
答案 0 :(得分:0)
window.resize
事件是页面加载过程的一部分。除了document.ready
JQuery函数之外,它还会触发。因此,此代码将在页面首次加载时运行:
navInner.removeClass('show');
trigger.removeClass('nav-open');
如果要根据视口大小或设备方向显示/隐藏某些页面元素,请使用CSS Media Queries。