[英]How can I properly use jQuery to fix this fencepost case?
我有一個功能
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');
通過加高小於高度最高的元素的元素,將使所有h3
元素(作為service-column
類元素的元素的后代)具有相同的高度。
問題是循環
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});
不需要在第一次迭代時執行其主體-這樣就等於無用的操作。 我想從第二項開始,而不是these.each
。 這可能嗎?
jQuery有slice
。 從第二個元素切片(索引1)。 如果省略了結尾,它將切到結尾。
these.slice(1).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>
使用greater-than
選擇器選擇索引大於提供的所有元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.