Equal height columns in jQuery

2019-03-22 11:16发布

问题:

Hi I am looking for a jQuery based equal height columns. I know there are a lot of them floating around but my requirement is a bit different. I want to use these in a Mega Menu where thee are about 4-5 drop-downs and each drop-down has 3-4 columns.

I want all these 3-4 columns of equal height but not in all drop-downs, because the columns height will be different in the other drop-down depending on the content of that section.

I found a solution in MooTools which works perfect for my requirement. The MooTools code below makes all the columns in a particular div equal to it's parent div's height

The MooTools Code :

var Equalizer = new Class({
 initialize: function(elements) {
  this.elements = $$(elements);
 },
 equalize: function(hw) {
  if(!hw) { hw = 'height'; }
  var max = 0,
   prop = (typeof document.body.style.maxHeight != 'undefined' ? 'min-' : '') + hw; //ie6 ftl
   offset = 'offset' + hw.capitalize();
  this.elements.each(function(element,i) {
   var calc = element[offset];
   if(calc > max) { max = calc; }
  },this);
  this.elements.each(function(element,i) {
   element.setStyle(prop,max - (element[offset] - element.getStyle(hw).toInt()));
  });
  return max;
 }
});

Usage :

var columnizer = new Equalizer('.sizeMe').equalize('height'); //call .equalize() as often as you want!

Can somebody help me converting this code in jQuery please. Actually my entire template is jQuery based and just for this equal-height function I do not want to load another JavaScript library.

Kindly Help!

回答1:

Right, thought that might be useful so made it in to a jQuery plugin for you.

Demo: http://jsfiddle.net/AXqBb/

equalizer.js:

(function($) {
    String.prototype.capitalize = function() {
        return this.replace(/^(.)/, function (c) { return c.toUpperCase(); })
    };

    $.fn.equalize = function(hw) {
        if (!hw) {
            hw = 'height';
        }

        var max = 0;
        var prop = (typeof document.body.style.maxHeight != 'undefined' ? 'min' + hw.capitalize() : hw);
        var offset = 'offset' + hw.capitalize();

        this.each(function() {
            var calc = parseInt(this[offset]);
            if (calc > max) {
                max = calc;
            }
        });

        this.each(function() {
            $(this).css(prop, max - (parseInt(this[offset]) - $(this)[hw]()));
        });

        return max;
    };
})(jQuery);

Called like this:

var maxHeight = $('.sizeMe').equalize('height');

I have kept the code as similar to what you posted as possible, so you can see the changes, so apologise for any bad style - hopefully it is attributable towards the original author. ;-)

NB. I added a basic first-word capitalisation function to String within this code; if already defined that would need to be removed.



标签: jquery height