2010-10-24 31 views
2

這是我的代碼。挑選所有元素的最大高度

v=dom.find("ul:first").outerHeight(); // the height of the first li element 
      // instead of taking the height of the first li element, it should loop through all 
      // li elements and set v to the element with the biggest height 

在代碼中間的註釋幾乎解釋了一切。我需要遍歷所有李元素,並採取最大的高度,而不是採取第一個元素的高度。

回答

3
var v = 0; 
// ... 
dom.find('ul:first').children('li').each(function() { 
    var height = $(this).outerHeight(); 
    v = height > v ? height : v; 
}); 
+0

謝謝。它效果很好。 – Peter 2010-10-24 15:44:05

+0

不錯的答案,代碼是相當乾淨的條件運算符 – kobe 2010-10-24 16:49:22

+0

有人可以請詳細說明條件運算符部分?它很乾淨,但我還不明白。 – MauF 2012-12-04 16:49:04

1

您可以使用jquery .each()方法遍歷每個元素,並使用.height()方法確定元素的高度。確定最大高度,聲明變量maxheight = 0,如果元素高度大於maxheight,則將maxheight設置爲元素高度。

var maxheight = 0; 
$('ul').each(function(index) { 
    if($(this).outerHeight() > maxheight) maxheight = $(this).outerHeight(); 
}); 
0
var el, max = 0; 
$("ul").each(function(){ 
    var height = $(this).outerHeight(); 
    if (height > max) { 
    el = this; 
    max = height; 
    } 
}); 
0
var maxHeight = Math.apply(null, $('ul:first > li').map(function() { 
    return $(this).outerHeight(); 
})); 

這工作爲好,只是沒有額外的變種。