在导航栏元素外部单击时,如何关闭打开的折叠导航栏?目前,打开或关闭它的唯一方法是单击导航栏切换按钮。
示例和代码请参见here:
到目前为止,我已经尝试了以下似乎不起作用的方法:
$(document).ready(function () {
$(document).click(function () {
// if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
// }
});
});但是上面的方法不起作用。
发布于 2021-10-26 06:54:54
最简单的方法是将click eventlistener附加到body标记。
document.body.addEventListener('click', (e) => {
if($(".navbar-collapse").hasClass("in")){
$('.navbar-collapse').collapse('hide');
}
})发布于 2021-10-26 06:56:53
您可以定义函数并在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>
发布于 2021-10-26 07:05:26
您应该在文档上添加一个事件侦听器,并检查单击是否在导航栏之外:
// 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');
});https://stackoverflow.com/questions/69718550
复制相似问题