【问题标题】:Close bootstrap dropdown only when mouse is clicked outside of dropdown仅当在下拉列表之外单击鼠标时才关闭引导下拉列表
【发布时间】:2019-02-09 11:28:21
【问题描述】:

我有一个引导下拉菜单:

<div class="dropdown>
   <a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="@imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>

  <ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>

现在 ul 通过 ajax 调用在页面加载时加载产品。问题是当我单击下拉列表中的任何产品时,下拉列表会关闭。但是我只想在 ul 之外的任何地方单击鼠标时才关闭下拉列表

【问题讨论】:

标签: javascript jquery css html twitter-bootstrap


【解决方案1】:

试试这样的:

$(document).click(function(e) {
  // get the clicked element
  $clicked = $(e.currentTarget);
  // if the clicked element is not a descendent of the dropdown
  if ($clicked.closest('.dropdown').length === 0) {
    // close the dropdown
    $('.dropdown').removeClass('open');
  }
});

【讨论】:

    【解决方案2】:

    2021 年你会这样做:

    $('.dropdown').on({
        "shown.bs.dropdown": function() { /* whatever you want to do when it fires */ },
        "click":             function(e) { // handles click event
          
           console.log(e.target) // just to check which element is on top
    
          if($('.dropdown-menu').is(e.target)) { // if dropdown is clicked
            this.closable = false // do not close it
            return;
          } else {
            this.closable=true; // else close it 
          }
    
        },
        "hide.bs.dropdown":  function() { return this.closable; } // save state
      });
    }
    

    【讨论】:

      【解决方案3】:

      只需将此脚本放在您的代码中

      <script>
          $(document).click(function() {
          $(".dropdown").removeClass('open');
      });
      </script>
      

      【讨论】:

      • 感谢您的回答,但不幸的是它没有工作。在 ul“productDD”中单击鼠标时,我不想关闭下拉菜单
      • 也许尝试使用blur 事件?正如hereThe blur event is sent to an element when it loses focus. (...) In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.所说的那样
      【解决方案4】:

      Bootstrap 有一个内置的解决方案

      &lt;a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown" data-bs-auto-close="outside"&gt;&lt;img ... /&gt;&lt;/a&gt;

      【讨论】:

        猜你喜欢
        • 2019-01-05
        • 2017-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 2019-01-27
        • 1970-01-01
        • 2012-06-07
        相关资源
        最近更新 更多