Keep bootstrap dropdown when mouse is out

2019-05-24 12:58发布

I have a multilevel dropdown made with bootstrap, now when I navigate few levels deep and accidentally pointer comes out of current dropdown list, all lists are closed until 1st level. How can I keep all opened dropdowns open and close only when it is clicked outside dropdown? i.e. do the same when mouse is clicked on outer space, not when just moved there.

Here is my demo: http://jsfiddle.net/n8XJb/

<ul class="nav nav-pills">
    <li class="dropdown">
      <a href="#" data-toggle="dropdown" class="dropdown-toggle">Dropdown <b class="caret"></b></a>
      <ul class="dropdown-menu" id="menu1">
        <li class="dropdown-submenu">
          <a href="#">Level 1</a>
          <ul class="dropdown-menu">
            <li class="dropdown-submenu">
              <a href="#">Level 2</a>
              <ul class="dropdown-menu">
                <li><a href="#">Level 3</a></li>
              </ul>
            </li>
          </ul>
        </li>
      </ul>
    </li>
</ul>

When you navigate to Level 3, and then mouse pointer comes out of current list, it goes back to Level 1 instantly.

1条回答
男人必须洒脱
2楼-- · 2019-05-24 13:46

I have solved it by some custom event handling (http://jsfiddle.net/n8XJb/2/):

jQuery('.dropdown-menu li a').mouseover(function(e) {
    e.stopPropagation();
    jQuery(this).parent().parent().find('li').each(function() {
        jQuery(this).removeClass('open');
    });
    jQuery(this).parent().addClass('open');
});

jQuery('.dropdown-toggle').click(function(e) {
    jQuery(this).parent().find('li').each(function() {
        jQuery(this).removeClass('open');
    });
});

Bootstrap uses class open for open dropdowns, so we can set/unset it manually whenever needed.

查看更多
登录 后发表回答