Keep bootstrap dropdown when mouse is out

2019-05-24 13:33发布

问题:

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:

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.