I'm trying to do something that I think should be pretty straightforward but I have not found a straightforward explanation of the solution.

I am building a responsive website that is mobile first (320px width as the default). At that small resolution, the site is one column and I am happy to allow each individual "box" to expand or contract to the natural height of the contents contained inside.

However, at larger resolutions where the site expands to three columns, I want to add a small Javascript function to equalize the heights of the boxes of each column. The function I am talking about would be something like this:

    jQuery(document).ready(function() {
    setHeight('#inner-footer .widget-area');
});

var maxHeight = 0;
function setHeight(column) {
    //Get all the element with class = col
    column = $(column);
    //Loop all the column
    column.each(function() {       
        //Store the highest value
        if($(this).height() > maxHeight) {
            maxHeight = $(this).height();;
        }
    });
    //Set the height
    column.height(maxHeight);
}

I've found different ways to do what I'm talking about.

  1. I can use the modernizr "load" function (formally yesnope.js).
  2. Using a custom function that incorporates Nicholas Zakas "isMedia" function as described in this link Media Specific Javascript or
  3. a custom javascript function using the the "screenWidth" variable as in
    var screenWidth = (screen.width < 768) ? true : false;
    as described in Media queries in the real world

With my limited javascript knowledge, I have been unable to actually write the code to get any of these approaches to work for my script. Can anyone help me out here?

I have no particular preference for approach I just want it to work cross browser, etc. My sense is that the modernizr approach is the most robust and stable way to make this work in the greatest number of use cases but I'm not totally sure of that. I've never modified modernizr so I'm unsure of how to write and where to put the custom load function.

Anyone have thoughts and specific code for the modernizr approach or any of the other solutions (or something else)? I greatly appreciate the assistance.

有帮助吗?

解决方案

Modernizr can check that media queries apply with the Modernizr.mq() function

You pass it your media query that you want it to match like this

if(Modernizr.mq('all and (min-width: 768px)')) {
    // Equal height code here
}

Here once the min width is past 768px then the code inside the function would be called, so for you the equal height code.

其他提示

You can try to make use of matchMedia, this will allow you to load specific js based on media queries.

https://developer.mozilla.org/en/DOM/window.matchMedia

Paul Irish has been working on some polyfills

https://github.com/paulirish/matchMedia.js/

Hope this helps

Ian

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top