jQuery基于活动的侧边栏子菜单

时间:2018-10-10 19:51:13

标签: javascript jquery ruby-on-rails

我有一个使用Bootstrap 4构建的侧边栏菜单。要创建一个使用jQuery进行扩展的子菜单。看起来像这样:

<div class="container-fluid">
  <div class="row">
    <nav class="col-md-1 d-none d-md-block sidebar">
      <div class="sidebar-sticky">
        <ul class="nav flex-column">
          <li class="nav-item">
            <a class="nav-link d-flex align-items-center flex-column sidebar" href="#" data-toggle="collapse" data-target="#submenu" aria-expanded="false" id="sidebarCollapse" >
             <%= image_tag 'products.png' %>
             <p>Products</p>
            </a>
          </li>
        </ul>
      </div>
    </nav>
    <!--Product Sidebar-->
<nav id="sidebar">
    <div class="sidebar-header">
        <h3>Bootstrap Sidebar</h3>
    </div>

    <ul class="list-unstyled components">
        <li class="active">
            <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">
                Main Item
            </a>
            <ul class="collapse list-unstyled" id="homeSubmenu">
                <li>
                    <a href="#">Item 1</a>
                </li>
                <li>
                    <a href="#">Item 2</a>
                </li>
                <li>
                    <a href="#">Item 3</a>
                </li>
            </ul>
        </li>

    </ul>
</nav>
    <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4">
      <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">Dashboard</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
          <div class="btn-group mr-2">
            <button class="btn btn-sm btn-outline-secondary">Share</button>
            <button class="btn btn-sm btn-outline-secondary">Export</button>
          </div>
        </div>
      </div>

      <canvas class="my-4 w-100" id="myChart" width="900" height="380"></canvas>
    </main>
  </div>
</div>

然后是jQuery:

$(document).ready(function () {
  $('#sidebarCollapse').on('click', function () {
  $('#sidebar').toggleClass('active');
  });
 });

这通常可以正常工作。单击产品的锚标记,子菜单/边栏将在右侧打开。但是问题是当未激活时,它将显示Bootstrap边栏和Main Item。如何获取它,以便在不活动时侧边栏具有隐藏的可见性?

我没有用运气尝试过以下jQuery:

$(document).ready(function () {
  $('#sidebar').hide();
    $('#sidebarCollapse').on('click', function (e) {
        e.preventDefault();
        $('#sidebar', this).toggle('active');
    });

});

1 个答案:

答案 0 :(得分:1)

您是否设置了CSS以使其最初隐藏?

#sidebar {
display:none;
}
#sidebar.active{
display:block;
}