简体   繁体   中英

How can I close the sidebar menu? (Bootstrap)

I have a side-menu on my bootstrap webpage which is open by default. If the screen is too small there is a button placed behind it to open the menu again.

When a user clicks on a link I would like the menu to close automatically.

The button I already have opens the menu perfectly, but I have no way of closing it?

<div id="wrapper">
        <div id="sidebar-wrapper">
            <ul class="sidebar-nav">
                <li class="sidebar-brand"><a href="#/"><img src="/content/img/AAA.png" width="27px" />Menu</a></li>
                <li data-ng-hide="!authentication.isAuth"><a href="#/Page2">Welcome {{authentication.userName}}</a></li>
                <li data-ng-hide="!authentication.isAuth"><a href="#/Page2">Page1</a></li>
                <li data-ng-hide="!authentication.isAuth"><a href="" data-ng-click="logOut()">Logout</a></li>
                <li data-ng-hide="authentication.isAuth"><a href="#/login"><span class="glyphicon glyphicon-user"></span> Login</a></li>
                <li data-ng-hide="authentication.isAuth"><a href="#/signup"><span class="glyphicon glyphicon-log-in"></span> Sign Up</a></li>
            </ul>
        </div>
    </div>

    <a href="#menu-toggle" class="btn btn-default" id="menu-toggle">
        Menu
    </a>

    <script>
        $("#menu-toggle").click(function (e) {
            e.preventDefault();
            $("#wrapper").toggleClass("toggled");
        });
    </script>

You could add in another event handler for the a elements.

    $(".sidebar-nav li a").click(function() {
        $("#wrapper").removeClass("toggled");
    });

Here are a few things that you could do:

  • You could use hide/show with jQuery(I can see you are already using it).
  • Instead of makeing a "toggled" class, Bootstrap has a built in "hidden" class that you could use.
  • You could also toggle it's css "display" value.
  • You could use the "animate" class to slide the menu on and off the screen.
  • You could have a variable to store the state of the menu("true" for out, "false" for in), and change it when the toggle button is clicked.

I had a similar issue, and I placed a close button on the menu, and added a seperate click handler that would close the menu. The close button would then hide with the menu, leaving just the button to open the menu again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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