我有一个Bootstrap导航栏,当缩小/点击切换按钮时,缩小时会折叠并作为菜单下拉。但是,一旦打开,它将保持打开状态,直到再次单击切换按钮。当用户A)在菜单区域外点击时,有没有办法自动关闭它,B)在移动设备上向上或向下滚动页面?以下是折叠时导航栏的外观:
这是下拉列表:
当点击黄色区域或任何菜单项时(搜索框除外),我需要下拉列表折叠。到目前为止,我的JS看起来像这样:
// prevent search box from vanishing upon click in responsive mode
$('input.form-control').click(function(e) { e.stopPropagation(); });
// re-collapse nav dropdown menu after selection (in responsive mode)
$('.navbar-fixed-top').click('li', function() {
$('.navbar-collapse').collapse('hide');
});
// close drop-down nav when user clicks outside
$(document).ready(function () {
function CloseNav() {
$(".navbar-collapse").stop().css({ 'height': '1px' }).removeClass('in').addClass("collapse");
$(".navbar-toggle").stop().removeClass('collapsed');
}
$('html').click(function (event) {
var clickover = $(event.target);
var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
if (_opened === true && !clickover.hasClass("navbar-toggle")) {
CloseNav();
}
});
});
这是相关的HTML代码段:
<!-- Nav bar -->
<div class="navbar navbar-default navbar-fixed-top top-nav" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="bootstrap/img/gray_logo.png" class="site-logo"><span class="site-name-first">Always</span><span class="site-name-second">Spanish</span></a>
</div>
<!-- Navbar links -->
<div class="collapse navbar-collapse" ng-controller="HeaderController">
<!-- Search box start -->
<form class="navbar-form navbar-right search-box" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
<!-- Search box start -->
<ul class="nav navbar-nav pull-right">
<li ng-class="{ active: isActive('/about')}"><a href="#about">About</a></li>
<li ng-class="{ active: isActive('/blog')}"><a href="#blog">Blog</a></li>
<li><a href="#">Premium</a></li>
<li><a href="#">Books</a></li>
<li><a href="javascript:;" data-target="#contact" data-toggle="modal">Contact</a></li>
</ul>
</div>
</div>
</div>
在3个JS脚本中,前两个似乎工作正常。这只是最后一个没有的。另外,我还不知道如何对滚动事件进行分析。我相信我在做一些非常愚蠢的事情。请帮忙!
答案 0 :(得分:0)
听取窗口上的所有点击,并检查这里是否有没有父级的导航栏。您可以使用closest
https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
Polyfill:https://github.com/jonathantneal/closest