避免在外部单击时关闭下拉菜单

时间:2019-03-12 11:59:14

标签: jquery bootstrap-4

通过单击外部避免下拉菜单关闭。仅单击按钮时显示和隐藏下拉菜单。这是fiddle

<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
  <span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a href="#">HTML</a></li>
    <li><a href="#">CSS</a></li>
    <li><a href="#">JavaScript</a></li>
  </ul>
</div>

2 个答案:

答案 0 :(得分:3)

Bootstrap 4下拉事件与Bootstrap 3稍有不同,因此suggested duplicates(和here)将起作用,以防止下拉菜单在外部点击时关闭。

对于 Bootstrap 4 (Bootstrap 4),look for the clickEvent,如果在hide事件中发现该事件,请防止默认关闭行为。仅当单击按钮时,此下拉菜单才会关闭。

$('#myDD').on('hide.bs.dropdown', function (e) {
    if (e.clickEvent) {
      e.preventDefault();
    }
})

Demo


在某些情况下,您可能希望单击按钮菜单时关闭下拉菜单。在这种情况下,您可以检查clickEvent目标。例如,寻找“ nav-link”类。

$('#myDD').on('hide.bs.dropdown', function (e) {
    if (e.clickEvent && e.clickEvent.target.className!="nav-link") {
      e.preventDefault();
    }
});

Demo 2

答案 1 :(得分:0)

我认为您只需要创建自己的菜单切换click事件,而不是使用一个引导程序即可,然后尝试覆盖所有内容

引导程序3

var $ddlBtn = $("#my-custom-ddl");
$ddlBtn.on("click", function(){
  var expanded = /true/i.test($ddlBtn.attr("aria-expanded"));
  $ddlBtn
    .attr("aria-expanded", !expanded)
    .parent().toggleClass("open");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />

<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" id="my-custom-ddl" aria-haspopup="true" aria-expanded="false">
    Dropdown Example
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="#">HTML</a></li>
    <li><a href="#">CSS</a></li>
    <li><a href="#">JavaScript</a></li>
  </ul>
</div>

引导程序4

var $ddlBtn = $("#my-custom-ddl");
$ddlBtn.on("click", function(){
  var expanded = /true/i.test($ddlBtn.attr("aria-expanded"));
  $ddlBtn
    .attr("aria-expanded", !expanded)
    .siblings(".dropdown-menu").toggleClass("show")
    .parent().toggleClass("show");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" id="my-custom-ddl" aria-haspopup="true" aria-expanded="false">
    Dropdown Example
    <span class="caret"></span>
  </button>
  <div class="dropdown-menu" aria-labelledby="my-custom-ddl">
    <a class="dropdown-item" href="#">HTML</a>
    <a class="dropdown-item" href="#">CSS</a>
    <a class="dropdown-item" href="#">Javascript</a>
  </div>
</div>