首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在HTML站点的导航栏元素之外单击时,如何关闭打开的折叠导航栏?

问在HTML站点的导航栏元素之外单击时,如何关闭打开的折叠导航栏?
EN

Stack Overflow用户
提问于 2021-10-26 06:47:37
回答 3查看 53关注 0票数 3

在导航栏元素外部单击时,如何关闭打开的折叠导航栏?目前,打开或关闭它的唯一方法是单击导航栏切换按钮。

示例和代码请参见here:

到目前为止,我已经尝试了以下似乎不起作用的方法:

代码语言:javascript
复制
$(document).ready(function () { 
    $(document).click(function () {
        // if($(".navbar-collapse").hasClass("in")){
            $('.navbar-collapse').collapse('hide');
        // }
    });
});

但是上面的方法不起作用。

EN

回答 3

Stack Overflow用户

发布于 2021-10-26 06:54:54

最简单的方法是将click eventlistener附加到body标记。

代码语言:javascript
复制
document.body.addEventListener('click', (e) => {
    if($(".navbar-collapse").hasClass("in")){
        $('.navbar-collapse').collapse('hide');
    }  
})
票数 1
EN

Stack Overflow用户

发布于 2021-10-26 06:56:53

您可以定义函数并在mouseleave上调用。下面是一个示例:

​

代码语言:javascript
复制
function showMeTheMoney() {
  $('.treasure').toggle();
}
代码语言:javascript
复制
.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;
}
代码语言:javascript
复制
<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>

​

票数 0
EN

Stack Overflow用户

发布于 2021-10-26 07:05:26

您应该在文档上添加一个事件侦听器,并检查单击是否在导航栏之外:

代码语言:javascript
复制
// 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');
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69718550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档