2012-01-13 45 views
9
元素

我已經做了一個快速Jsbin的寬度:http://jsbin.com/ujabew/edit#javascript,html,live計算最大的一組使用jQuery

我想要做到的,是找出哪些是最大的<section>出3從鏈接的。所以我想要的是,在循環運行後,將var width設置爲任何寬度可能的最大可能數。正在進行

代碼張貼在鏈接

+3

Insteading,跟蹤迄今爲止發現的最大的寬度。 'var max = 0;循環(如果this.width> max then max = this.width);'在僞代碼中。 – 2012-01-13 16:16:23

+0

@MarcB這是相當不錯的僞代碼給我。 – 2012-01-13 16:23:33

回答

31

這裏:

var maxWidth = Math.max.apply(null, $(elems).map(function() { 
    return $(this).outerWidth(true); 
}).get()); 

現場演示:http://jsfiddle.net/rM4UG/

+0

這是一個不錯的。 – powerbuoy 2012-01-13 16:27:13

+0

很簡單,做得好 – einar 2012-01-13 17:03:39

+0

不錯的一個。當我使用它時,它只是在身體內有元素的元素:auto(用於居中目的)。如果你在IE(標準模式)中做類似的事情,刪除傳入'outerWidth'函數的真實值,以便從計算中刪除邊距,並且你是黃金! – 2012-01-24 16:15:25

0

我相信你想看看在underscore庫。具體而言,最大的方法

0
$(document).ready(function(){ 
    var maxWidth = 0; 
    $('section').each(function(){ 
    w = $(this).outerWidth(true);  
    if (w > maxWidth) 
      maxWidth = w; 
    }); 
}); 
2

充實馬克B的評論,使用Math.max()

$(document).ready(function(){ 
    var maxWidth = 0; 
    $('.content ul li').each(function(){ 
    var itemWidth = $(this).outerWidth(true); 
    maxWidth = Math.max(maxWidth, itemWidth) 
    }); 
}); 
0

更改.each()循環到S:

var thisWidth = $(this).outerWidth(true); 

if (thisWidth > width) { 
    width = thisWidth; 
} 
0

這是我的主意

$(文件)。就緒(函數(){

var elements = $('.content ul li'); 
var count = elements.length -1; 
var width = [];   

elements.each(function(n){ 
    width.push($(this).outerWidth(true)); 
    if (count == n) { 

     width = Math.max.apply(Math, width); 

    } 
}); 

});

我添加了元素數的數量,並且運行Math.max來獲得每個循環完成時的最大數量。

0

我剛寫了一個關於這個的函數。我認爲這可能會幫助其他人。 (的jQuery)的只是增加寬度

$.fn.largerWidth = function() { //function(p) 
            // where 'p' can be clientWidth or offsetWidth 
            // or anything else related to width or height 
    var s = this,m; 
    for (var i = 0; i < s.length; i++) { 
     var w = s[i].offsetWidth; // s[i][p]; 
     (!m || w > m) ? (m = w) : null 
    } 
    return m; 
}