简体   繁体   English

如何用jquery关闭bootstrap下拉菜单?

[英]How to close a bootstrap dropdown menu with jquery?

Alright, I asked a question yesterday that turned out to be completely off base. 好吧,我昨天问了一个问题,结果证明完全不合适。 I think I'm on more solid ground now but still having an issue. 我认为我现在处于更加坚实的基础上,但仍然存在问题。 I have a bootstrap dropdown menu in a button group as follows: 我在按钮组中有一个bootstrap下拉菜单,如下所示:

<div class="btn-group" id="openItems">
    <button class="btn btn-custom-top dropdown-toggle" data-toggle="dropdown"><span class="caption"></span><span class="caret"></span></button>
    <ul class="dropdown-menu" id="openItemDropdown">
    </ul>
</div>

After moving the mouse out of the menu, I'd like it to close. 将鼠标移出菜单后,我希望它能够关闭。 I almost have it working but not quite. 我几乎让它工作但不完全。

$(document).ready(function ()
{
    $('.dropdown-menu').mouseleave(function ()
    {

        $(".dropdown-toggle").dropdown('toggle');
    });
});

The problem with this is that it toggles all of the dropdowns on the page. 这个问题是它切换了页面上的所有下拉菜单。 I've tried checking .hasClass('active') on $(this) but it always returns false. 我已经尝试在$(this)上检查.hasClass('active') ,但它总是返回false。 I suspect this is because $(this) is actually the .dropdown-menu node rather than the .dropdown-toggle node. 我怀疑这是因为$(this)实际上是.dropdown-menu节点而不是.dropdown-toggle节点。 However, traversing the nodes is tricky and doesn't seem to work across all browsers. 但是,遍历节点很棘手,似乎并不适用于所有浏览器。 There has GOT to be a way to just always close the lists rather than toggling them. 有GOT是一种总是关闭列表而不是切换它们的方法。

just add a custom fake class along with dropdown-toggle. 只需添加一个自定义假类以及下拉切换。 for example: 例如:

<div class="btn-group" id="openItems">
  <button class="btn btn-custom-top myFakeClass dropdown-toggle" data-toggle="dropdown">
    <span class="caption"></span>
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" id="openItemDropdown"></ul>
</div>

then use that as a selector in the script : 然后将其用作脚本中的选择器:

$(document).ready(function () {
  $('.dropdown-menu').mouseleave(function () {
    $(".myFakeClass").dropdown('toggle');
  });
});

There's an even easier way to close a Bootstrap dropdown with jQuery: 使用jQuery关闭Bootstrap下拉列表有一种更简单的方法:

$j(".dropdown.open").toggle();

This will close all open dropdowns. 这将关闭所有打开的下拉菜单。

Alternately, 交替,

$j(".dropdown.open").removeClass("open");

This, without any custom code. 这,没有任何自定义代码。 Of course, it does require you to use the .dropdown class, even when it is superfluous, as in the case of a btn-group . 当然,它确实需要你使用.dropdown类,即使它是多余的,就像在btn-group的情况下一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM