更新基于 cmets 我回去阅读并看到了您想要的解决方案,我采用了我的最终插件方案并展示了如何与您的完全相同的事情和阿米尔的评论。然而,他的回答与我在下面的第一个建议基本相同:
带插件:
$('.row').each(function(i) { $(this).find('.panel').equalHeights() });
Example
这很容易。只需在匹配的集合中找到最高的,然后将所有内容设置为该高度。或者,如果您想使用给定的高度,请使用它!
像这样:
var mh = 0;
$(".columns").each(function(i) { mh = mh > $(this).height() ? mh : $(this).height(); })
.height(mh);
Example
或者,如果您希望它作为一种快速而肮脏的 jQuery 方法:
$.fn.equalHeights = function (e) {
var mh = 0;
$(this).each(function(i) { mh = mh > $(this).height() ? mh : $(this).height(); });
return $(this).height(mh);
};
// use as:
$(".columns").equalHeights();
Example
|或|
如果你想把它作为一个完整的 jQuery 插件来使用,例如:
$(".four").equalHeights(); // set all elements matching selector to height of tallest
$(".four").equalHeights(100); // set all elements matching selector to height of integer given
$(".four").equalHeights('200'); // set all elements matching selector to height of string given
// Same as top 3 but written alternatly in accordance with jQuery mark-up style
$.equalHeights(".four"); || $.equalHeights($(".four"));
$.equalHeights($(".four"), 100);
$.equalHeights($(".four"), '200');
只需添加以下完整插件:
(function($) {
if (!$.equalHeights) {
$.extend({
equalHeights: function() {
var args = arguments,
elm,
mh = 0;
if (args.length) {
for (x in args) {
switch (typeof args[x]) {
case 'number':
mh = args[x];
break;
case 'object':
if (args[x] instanceof jQuery) elm = args[x];
break;
case 'string':
if (!elm) {
if ($(args[x]).length) elm = $(args[x]);
else if (!mh) if (args[x].replace(/\D/g, '')) mh = args[x].replace(/\D/g, '');
}
else if (!mh) if (args[x].replace(/\D/g, '')) mh = args[x].replace(/\D/g, '');
break;
}
}
}
if (elm instanceof jQuery) {
if (!mh) elm.each(function(i) { mh = mh > $(this).height() ? mh : $(this).height(); });
return elm.height(mh);
}
else {
return 'Error: Cannot find Selector';
}
}
});
$.fn.extend({
equalHeights: function() {
var args = [$(this)];
if (arguments.length) for (x in arguments) args.push(arguments[x]);
return $.equalHeights.apply($, args);
}
});
}
})(jQuery);
Example
插件的编译版本:
(function($){$.equalHeights||($.extend({equalHeights:function(){var a=arguments,c,b=0;if(a.length)for(x in a)switch(typeof a[x]){case "number":b=a[x];break;case "object":a[x]instanceof jQuery&&(c=a[x]);break;case "string":c?b||a[x].replace(/\D/g,"")&&(b=a[x].replace(/\D/g,"")):$(a[x]).length?c=$(a[x]):b||a[x].replace(/\D/g,"")&&(b=a[x].replace(/\D/g,""))}return c instanceof jQuery?(b||c.each(function(a){b=b>$(this).height()?b:$(this).height()}),c.height(b)):"Error: Cannot find Selector"}}),$.fn.extend({equalHeights:function(){var a=[$(this)];if(arguments.length)for(x in arguments)a.push(arguments[x]);return $.equalHeights.apply($,a)}}))})(jQuery);