2009-06-18 74 views
17

我試過找到一個可以理解的答案,但放棄了。用jQuery計算兒童的總寬度

爲了有dymnamic內容(如博客文章和圖片)在水平網站(就像thehorizontalway.com)必須在pixles設定一個固定的寬度爲體,對不對? 因爲你使用浮動元素,否則會打破和包裝頁面,這取決於瀏覽器的寬度。

編輯!這個具體的值可以是計算jQuery,謝謝你:)在這個例子中,一個額外的值被添加到總大小,它可以用於浮動元素之前的內容。現在身體獲得動態寬度!

我最初的想法是讓jQuery的計算是爲我們: ( '各自崗位WIDTH' * '的帖子數')+ 250(用於額外的內容)

HTML代碼

<body style="width: ;"> <!-- Here we want a DYNAMIC value --> 
<div id="container"> 
    <div id="menu"></div> <!-- Example of extra content before the floats --> 
    <div class="post">Lorem</div> 
    <div class="post">Lorem</div> 
    <div class="post">Lorem</div> <!-- Floated elements that we want the sizes of --> 
    <div class="post">Lorem</div> 
</div> 
... 
<!-- So if these posts were 300px exept the last that was 500px wide, then the BODY WIDTH should be (300+300+300+500) + 250 [#menu] = 1650px --> 

Alconja的結果和答案

$(document).ready(function() { 
var width = 0; 
$('.post').each(function() { 
    width += $(this).outerWidth(true); 
}); 
$('body').css('width', width + 250); 
}); 

非常感謝!

回答

35

看起來你已經得到它非常正確的...一對夫婦的音符,但:

  • .outerWidth(true)包括填充&保證金(因爲你傳遞true),所以沒有必要去嘗試&再次添加。
  • .outerWidth(...)只返回第一個元素的寬度,所以如果每個元素是不同的大小,乘以帖子的數量將不是一個精確的總寬度值。

考慮到這一點這樣的事情應該給你你以後在做什麼(讓你的250初期填補,我以爲是菜單&東西?):

var width = 0; 
$('.post').each(function() { 
    width += $(this).outerWidth(true); 
}); 
$('body').css('width', width + 250); 

是否幫助,或者是否還有其他一些具體問題(從您的問題中不太清楚)?

+0

太棒了,那正是我的意思。稍後我會編輯問題,以便更清楚地說明我在說什麼。就像你說的那樣,我只用第一個.post代碼,然後用.size()來計算剩餘的代碼 - 這使得它更容易製作水平滾動頁面,使得頁面的寬度變爲每頁動態的寬度:)需要添加一些無腳本超級體寬,並完成。 – elundmark 2009-06-19 01:44:52

0

你可以用這個單行程計算寬度,雖然比我想象的要長。

var width = $('.post').map(function(undefined, elem) { 
    return $(elem).outerWidth(true); 
}).toArray().reduce(function(prev, curr) { 
    return prev + curr; 
}, 0);