单击导航条元素外部时,如何关闭打开的折叠导航条?目前,打开或关闭它的唯一方法是单击导航栏切换按钮。
查看这里的示例和代码:
到目前为止,我已经尝试了以下似乎不工作:
$(document).ready(function () {
$(document).click(function () {
// if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
// }
});
});
但上述方法不起作用
最简单的方法是在body标签上附加一个click eventlistener。
document.body.addEventListener('click', (e) => {
if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
}
})
您可以定义一个函数并在mouseleave
上调用。下面是一个例子:
function showMeTheMoney() {
$('.treasure').toggle();
}
.treasure {
background:blue;
color:white
width:100px;height:50px;
position:absolute;bottom:0;right:0;
display:none;
}
div {
height:200px;width:200px;
}
.somespan {
width:100px;
height:100px;
background:yellow;
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="somespan" onmouseleave="showMeTheMoney();">Hover this red span and leave it with your mouse to reveal the treasure</span>
<span class="treasure">The treasure is found.</span>
</div>
您应该在文档上添加一个事件侦听器,并检查单击是否在导航条之外:
// listen to clicks in document
document.addEventListener("click", (evt) => {
let targetElement = evt.target;
const navbar = document.querySelector('.navbar-collapse');
const navbarToggler = document.querySelector('.navbar-toggle');
do {
// open menu when click is on toggle button and menu does not have the 'in' class
if (targetElement == navbarToggler && ! navbar.classList.contains('in')) {
navbar.classList.add('in');
return;
}
// do nothing when clicked in navbar
else if (targetElement == navbar) {
return;
}
// Go up the DOM
targetElement = targetElement.parentNode;
} while (targetElement);
// when clicked outside of navbar
navbar.classList.remove('in');
});