在容器/正文单击上关闭Bootstrap下拉列表

时间:2016-02-13 23:55:26

标签: javascript jquery css twitter-bootstrap

我在Bootstrap的下拉列表中添加了一些动画,但现在关闭它的唯一方法是单击按钮。我不是很有经验,我希望得到一些帮助,我想要的是在点击容器/身体时关闭它。

$('.dropdown-toggle').click(function() {
  $(this).siblings('.dropdown-menu').toggleClass('expanded');
});
body {
  margin: 50px 0 0 250px;
}
.dropdown .dropdown-menu {
  display: block;
  -moz-transition: opacity 0.2s ease-out 0s, -moz-transform 0.2s ease-out 0s, visibility 0s ease-out 0.1s;
  -o-transition: opacity 0.2s ease-out 0s, -o-transform 0.2s ease-out 0s, visibility 0s ease-out 0.1s;
  -webkit-transition: opacity 0.2s ease-out, -webkit-transform 0.2s ease-out, visibility 0s ease-out;
  -webkit-transition-delay: 0s, 0s, 0.1s;
  transition: opacity 0.2s ease-out 0s, transform 0.2s ease-out 0s, visibility 0s ease-out 0.1s;
}
.dropdown .dropdown-menu.collapsed {
  opacity: 0;
  -moz-transform: translateY(0);
  -ms-transform: translateY(0);
  -webkit-transform: translateY(0);
  transform: translateY(0);
  visibility: hidden !important;
}
.dropdown .dropdown-menu.expanded {
  opacity: 1;
  -moz-transform: translateY(12px);
  -ms-transform: translateY(12px);
  -webkit-transform: translateY(12px);
  transform: translateY(12px);
  visibility: visible !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle">
    Dropdown
  </button>

  <ul class="dropdown-menu collapsed" aria-labelledby="dropdownMenu1">
    <li><a href="#">Action</a>
    </li>
    <li><a href="#">Another action</a>
    </li>
    <li><a href="#">Something else here</a>
    </li>
    <li role="separator" class="divider"></li>
    <li><a href="#">Separated link</a>
    </li>
  </ul>
</div>

2 个答案:

答案 0 :(得分:1)

您可以通过向正文文档添加点击功能来实现此目的,然后检查目标 id < / strong>并基于您选择要做的事情,这里是您案例的摘要

$(document).click(function (e) {
    var clicked = $(e.target);
    var opened = $(".dropdown-menu").hasClass("expanded");
    if (opened === true && !clicked.hasClass("dropdown-toggle")) {
        $(".dropdown-toggle").click();
    }
});
这是一个小提琴: https://jsfiddle.net/9duqrovc/1/

答案 1 :(得分:0)

您应该使用以下内容添加自定义CSS类:

$('.dropdown').on('show.bs.dropdown', function (e) {
  // e.relatedTarget is the toggling anchor element
  e.relatedTarget.next().toggleClass('expanded');
})