簡體   English   中英

jQuery獲得子div的最大寬度

[英]jQuery get max width of child div's

我需要在包裝器div元素中獲取子div的最大寬度(僅一個寬度)

<div id="wrapper">  
    <div class="image"><img src="images/1.jpg"></div> 
    <div class="image"><img src="images/2.jpg"></div>  
    <div class="image"><img src="images/3.jpg"></div>  
    <div class="image"><img src="images/4.jpg"></div>  
    <div class="image"><img src="images/5.jpg"></div>  
    <div class="image"><img src="images/6.jpg"></div> 
</div>
Math.max.apply(Math, $('.image').map(function(){ return $(this).width(); }).get());

根據建議,我會打破這個:

$('.image').map(function(){
   return $(this).width();
}).get();

以上獲取所有.image div的列表,並將其轉換為寬度列表。 所以你現在有類似的東西: [200, 300, 250, 100, 400] 正如Felix指出的那樣, .get()是獲取實際數組而不是jQuery數組所必需的。

Math.max需要N個參數,因此您必須將其稱為: Math.max(200, 300, 250, 100, 400) ,這是Math.max.apply部分完成的。

一個不那么難以考慮的示例函數; 不像cwolves那樣優雅,但如果你是初學者,可能更容易理解。

function getMaxChildWidth(sel) {
    max = 0;
    $(sel).children().each(function(){
        c_width = parseInt($(this).width());
        if (c_width > max) {
            max = c_width;
        }
    });
    return max;
}

http://jsfiddle.net/userdude/rMSuJ/1/

我喜歡這種方法,因為它在核心可讀性和簡潔性之間達到了最佳點(IMHO):

var max_w = 0;
$('#wrapper div.image').each(function() {
    max_w = Math.max(max_w, parseInt($(this).width()));
})

YMMV當然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM