简体   繁体   中英

Using jQuery .hide() with CSS media queries for menu toggle based on screen resolution

I have a website using css media queries to detect browser resolution and modify my site accordingly.

I have run into a slight problem with my main navigation menu. There are a number of pages on my site where I would like to have my main navigation hidden on load for mobile resolutions, but displayed on desktop resolutions.

This seems like a simple enough task to accomplish with css, but unfortunately for me, it is not. I am unable to use both display:none; and visibility:hidden; because when my menu detects on load that it is hidden, it sets it's height to 0, and will not change.

Here is a stack overflow page reference: Setting a div to display:none; using javascript or jQuery

Ultimately, I the only option I found that would hide my menu on load, while still allowing the menu to correctly calculate it's height was the following bit of jQuery.

$(document).ready(function () {
    $(".hide-menu").hide();
    var $drillDown = $("#drilldown");
});

Now, this solution is working for pages that I would like to have the menu initially hidden on load for all screen resolutions. However, I have a number of pages on which I would like to have the menu hidden initially hidden on load for mobile, but displayed on desktop.

I have attempted to recreate this scenario in a jsfiddle: http://jsfiddle.net/WRHnL/15/

As you can see in the fiddle, the menu system has big issue with not being displayed on page load. Does anyone have any suggestions on how I might accomplish this task?

You can do it by comparing the screen-size:

$(document).ready(function () {
    var width = $(window).width();
    if (width < 768) {
        $(".hide-menu").hide();
    }
    var $drillDown = $("#drilldown");
});

You can use !important to force to origional state via media queries. This will over-ride the "display:none" from your js.

Example:

@media (max-width:980px){ 
nav  > .btn-group{display:none}
}

Your Js then toggles style="display:block" or style="display:none" you maximize the window and the below resets your origional style.

@media (min-width: 992px) {
nav  > .btn-group{margin:0px auto; display:inline-block !important}
}

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