多级下拉菜单项

时间:2017-05-31 16:59:07

标签: jquery css multi-level

如何更新此代码以在焦点丢失时隐藏菜单项。 进行选择并再次单击教程按钮后,所有菜单项仍然打开。

请尝试。

工作示例: https://www.w3schools.com/Bootstrap/tryit.asp?filename=trybs_ref_js_dropdown_multilevel_css&stacked=h

enter image description here



<!DOCTYPE html>
    <html>
    <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <style>
    .dropdown-submenu {
        position: relative;
    }
    
    .dropdown-submenu .dropdown-menu {
        top: 0;
        left: 100%;
        margin-top: -1px;
    }
    </style>
    </head>
    <body>
       
    <div class="container">
      <h2>Multi-Level Dropdowns</h2>
      <p>In this example, we have created a .dropdown-submenu class for multi-level dropdowns (see style section above).</p>
      <p>Note that we have added jQuery to open the multi-level dropdown on click (see script section below).</p>                                        
      <div class="dropdown">
        <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">Tutorials
        <span class="caret"></span></button>
        <ul class="dropdown-menu">
          <li><a tabindex="-1" href="#">HTML</a></li>
          <li><a tabindex="-1" href="#">CSS</a></li>
          <li class="dropdown-submenu">
            <a class="test" tabindex="-1" href="#">New dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
              <li><a tabindex="-1" href="#">2nd level dropdown</a></li>
              <li class="dropdown-submenu">
                <a class="test" href="#">Another dropdown <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#">3rd level dropdown</a></li>
                  <li><a href="#">3rd level dropdown</a></li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
    
    
    <script>
    $(document).ready(function(){
      $('.dropdown-submenu a.test').on("click", function(e){
        $(this).next('ul').toggle();
        e.stopPropagation();
        e.preventDefault();
      });
    });
    </script>
    
    </body>
    </html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以使用2个不同的功能分割切换按钮,以显示和隐藏ul。然后你可以在隐藏所有孩子的隐藏功能中添加代码。

这样的事可能会对你有所帮助:

$(document).ready(function(){
  $('.dropdown-submenu a.test').on("click", function(e){

    if ( $(this).next('ul').is(":visible") ) {
      $(this).children().hide();
    } else {
      $(this).next('ul').show();
    }

    e.stopPropagation();
    e.preventDefault();
  });
});

注意:我还没有测试过,所以我的代码可能包含错误,我只想告诉你我在想什么。