简体   繁体   中英

Jquery .slideToggle() with CSS media query

I have a mobile version of my website that changes according to the width, when the mobile width triggers the media query changes the menu to a drop down. The problem I am having is when a user click on the drop down and then hides it again, when expanding width to full view the menu remains hidden.

Jquery:

$(document).ready(function(){
$("#drop_button")
    .click(function(){
        $("#menu").stop();
        $("#menu").slideToggle();
    });
});

CSS:

#menu {
    width:30%;  
    float:left;
}

@media (max-device-width: 380px), (max-width: 380px){
    #menu{
        display:none;
        width:calc(100% - 20px);
        height:auto;
        padding:10px;
        font-size:1em;
    }
}

Any help would be appreciated.

.slideToggle() is messing with the CSS's display property.

There are a couple of ways to accomplish what you need, one is to:
Style with CSS Mobile-first (the other-way-around)
and use !important to override the styles added by jQuery slideToggle :

#menu{                      /* Mobile-first */
  background:#faf;
  display:none;
  width:calc(100% - 20px);
}
#drop_button{display:block;}

@media (min-width: 380px){    /* non-mobile Media Query */
  #menu{
    display:block !important; /* override jQuery styles */
    width:30%;  
    float:left;
  }
  #drop_button{display:none;}
}

jsBin demo

You'll still have a small issue you did not mentioned, and that's:
that if you open the Menu while Mobile, than you go to Desktop and back to Mobile, the Menu will wait you opened instead of being always hidden .
To fix that you can create a $(window).on("resize", fn) listener, get the viewport size and hide the menu (if was opened before on Mobile)

Was hoping to this in CSS however I have used Jquery:

    $( window ).resize(function() {
        if ($(window).width() > 380){
            $("#menu").css("display","inline");
            //Ensure menu is always visible if the window width is larger than 380px.
        }
        else
        {
            $("#menu").css("display","none");
            //Hide the menu any time the window is resized.
        }
    });

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