简体   繁体   中英

Bootstrap Mobile Menu Resizing to Desktop

I've built a custom mobile menu for my HTML page. This mobile menu sits at the bottom of the content and is hidden, until selected using the following:-

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"  aria-expanded="false" id="mobile-navigation-toggle">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
</button>

This is the standard hamburger menu icon that appears with Bootstrap on mobile. The custom mobile menu looks like this:-

<div id="menu" class="nav-collapse">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
        <li><a href="#">Home</a></li>
    </ul>
</div>

I then have a JS function that opens and closes this menu as I want it too, and this works fine.

$("#mobile-navigation-toggle").click(function() {
var expanded = $(this).attr('aria-expanded');

if(expanded == "true") {
    $(this).attr('aria-expanded','false');
    $("#main").animate({marginLeft:'0px'},'slow');   
}
else {
    $(this).attr('aria-expanded','true');
    $("#main").animate({marginLeft:'500px'},'slow');   
} 
});

I have a problem though when re-sizing from mobile to desktop - I want this mobile menu (which may or may not be expanded at the time), to slide shut and the main content be slid back. The mobile menu pushes in from the left.

I've written this, which works fine, but I feel like it might be quite hacky.

$(window).resize(function() {
    var width = $(window).width();
    console.log(width);

    <!-- Is there a better way of doing this? -->
    if(width >= 750) {
        $("#mobile-navigation-toggle").attr('aria-expanded','false');
        $("#main").animate({marginLeft:'0px'},'slow');  
    }
    <!-- End Is there a better way of doing this? -->
});

Is there a better way to test whether the bootstrap desktop/mobile menu is displaying than checking a width of 750 and sliding the menu shut?

Thanks in advance!

You can use @media query to detect the window width.

Just add to your css:

#main {
   transition:all .3s ease;
}

@media screen and (min-width: 480px) {
   #main {
       margin:0 !important;
   }
}

Also, you need to change the animate function in $("#main").animate({marginLeft:'0px'},'slow'); to css - the css transition will take care about the animation.

Notice that you have couple of #main in tour site. You should to fix this.

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