2009-06-18 121 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);