在 Bootstrap 3 中单击导航栏元素外部时如何关闭打开的折叠导航栏? [英] How to close an open collapsed navbar when clicking outside of the navbar element in Bootstrap 3?
问题描述
如何在导航栏元素外部单击时关闭打开的折叠导航栏?目前,打开或关闭它的唯一方法是点击 navbar-toggle
按钮.
How can I close an open collapsed navbar on clicking outside of the navbar element? Currently, the only way to open or close it is by clicking on the navbar-toggle
button.
查看这里的示例和代码:
到目前为止,我已经尝试了以下似乎不起作用的方法:
So far, I have tried the following which doesn't seem to work:
jQuery(document).click(function() {
});
jQuery('.navbar').click(function(event) {
jQuery(".navbar-collapse").collapse('hide');
event.stopPropagation();
});
推荐答案
看看:
$(document).ready(function () {
$(document).click(function (event) {
var clickover = $(event.target);
var _opened = $(".navbar-collapse").hasClass("navbar-collapse in");
if (_opened === true && !clickover.hasClass("navbar-toggle")) {
$("button.navbar-toggle").click();
}
});
});
您的小提琴适用于:http://jsfiddle.net/52VtD/5718/
它是 这个答案,缺少动画,也稍微复杂一点.
Its a modified version of this answer, which lacks the animation and is also a tiny bit more complicated.
我知道,调用 click()
不是很优雅,但是 collapse('hide')
对我也不起作用,我认为动画比几乎添加和删除类要好一些.
I know, invoking the click()
isn't very elegant, but collapse('hide')
did not work for me either, and i think the animation is a bit nicer than adding and removing the classes hardly.
这篇关于在 Bootstrap 3 中单击导航栏元素外部时如何关闭打开的折叠导航栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!