【问题标题】:How to close an open collapsed navbar when clicking outside of the navbar element in HTML site?在 HTML 站点中单击导航栏元素外部时如何关闭打开的折叠导航栏?
【发布时间】:2021-12-11 13:23:33
【问题描述】:

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

示例和代码见here

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

$(document).ready(function () { 
    $(document).click(function () {
        // if($(".navbar-collapse").hasClass("in")){
            $('.navbar-collapse').collapse('hide');
        // }
    });
});

但是上面的方法不行

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

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

    // 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');
    });
    

    【讨论】:

      【解决方案2】:

      您可以定义一个函数并调用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>

      【讨论】:

        【解决方案3】:

        最简单的方法是将点击事件监听器附加到正文标签。

        document.body.addEventListener('click', (e) => {
            if($(".navbar-collapse").hasClass("in")){
                $('.navbar-collapse').collapse('hide');
            }  
        })
        

        【讨论】:

          猜你喜欢
          • 2014-07-09
          • 2017-05-20
          • 2016-02-22
          • 2021-12-26
          • 1970-01-01
          • 2018-06-04
          • 2015-04-12
          • 1970-01-01
          • 2017-05-24
          相关资源
          最近更新 更多