我希望只有在窗口大于767px时才能在悬停时打开下拉列表。我尝试在页面加载时调用函数,并在窗口上调整宽度大小条件。 enableHover()函数仅适用于页面加载,而不适用于窗口大小调整。
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">dropdown link</a>
<a class="dropdown-item" href="#">dropdown link</a>
<a class="dropdown-item" href="#">dropdown link</a>
</div>
</li>
</ul>
</div>
</nav>
jQuery(document).ready(function($) {
//call dropdown hover and on load & resize
$( window ).resize(function() {
enableHover();
});
enableHover();
});
//emable hover when window > 767px
function enableHover() {
if ($(window).width() > 767) {
$('nav.navbar li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});
}
}
答案 0 :(得分:1)
您需要取消绑定悬停操作。您的.resize
功能正在运行,但没有任何内容从下拉列表中移除悬停操作。添加如下内容:
function enableHover() {
if ($(window).width() > 767) {
$('nav.navbar li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});
} else {
$('nav.navbar li.dropdown').unbind('mouseenter mouseleave')
}
}
这是一个有效的代码:
https://codepen.io/egerrard/pen/qPyYwR
或者更简单的解决方案就是使用css:
@media (min-width: 768px) {
.dropdown:hover .dropdown-menu {
display: block;
margin-top: 0;
}
}
@media (max-width: 767px) {
.dropdown:hover .dropdown-menu
display: none;
margin-top: auto;
}
请在此处查看: