我有一个函数
function giveTheseEqualHeight ( selector )
{
// selector: CSS selector of elements on the page to be forced to have the same height
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = these.first().height();
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});
these.height(maxHeight);
}
这是非常不言自明的。
示例用例:
giveTheseEqualHeight('.service-column h3');
将使属于 service-column
类元素的后代的所有 h3
元素具有相同的高度,方法是增加比最高高度小的元素。
问题是循环
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});
不需要在第一次迭代时执行它的主体——这相当于无用的操作。我想从第二项开始,而不是 these.each
。这可能吗?
最佳答案
如果获取高度数组然后使用原生 Math.max 取最大值,则可以避免计算第一个元素的高度:
function giveTheseEqualHeight(selector) {
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = Math.max.apply(null, these.map(function(el) {
return $(this).height();
}));
these.height(maxHeight);
}
这是一个演示:
function giveTheseEqualHeight(selector) {
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = Math.max.apply(null, these.map(function(el) {
return $(this).height();
}));
these.height(maxHeight);
}
giveTheseEqualHeight('div')
div {display: inline-block;background: #EEE; vertical-align: top;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Lorem</div>
<div>Test <br>rest</div>
<div>Test <br> and rest <br>on the <br>west</div>
关于javascript - 我怎样才能正确使用 jQuery 来修复这个 fencepost 案例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363157/