jquery - 用jQuery计算Children的总宽度

标签 jquery css dynamic layout

我试图找到一个可以理解的答案,但放弃了。

为了在水平网站(如 thehorizontalway.com )中拥有动态内容(如博客文章和图片),您必须为 BODY 设置固定宽度以像素为单位,对吗? 因为您在其中使用了 float 元素,否则会根据浏览器的宽度中断和包裹页面。

编辑! 这个特定的值可以用 jQuery 计算,谢谢 :) 在这个例子中,一个额外的值被添加到总大小,可用于 float 元素之前的内容。现在正文获得动态宽度!

我最初的想法是让 jQuery 为我们计算这个: ( 'EACH POSTS WIDTH' * 'NUMBER OF POSTS' ) + 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);
});

非常感谢!

最佳答案

看起来你做对了......不过有几点要注意:

  • .outerWidth(true)包括填充和边距(因为您传递的是 true ),因此无需再次尝试添加它。
  • .outerWidth(...)仅返回第一个元素的宽度,因此如果每个元素的大小不同,则将其乘以帖子数将不是总宽度的准确值。

考虑到这一点,像这样的东西应该会给你你想要的东西(保留你的 250 个初始填充,我认为这是用于菜单和东西?):

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

这有帮助吗,或者您是否遇到了其他一些具体问题(您的问题不是很清楚)?

关于jquery - 用jQuery计算Children的总宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1015669/

相关文章:

jquery - 在 jQuery 选择框中,当元素失去焦点时会触发更改事件

javascript - Kendo UI 网格绑定(bind)错误

javascript - 有没有办法在没有实例的情况下获取 css 类的值?

python - WTForms/ flask : Dynamic min_entries

c++ - 多新建一删除

JavaScript 更新变量名

html - 无法使用 CSS 下拉菜单

html - 带有两个全 Angular block 按钮的 Bootstrap 列

javascript - 多个粘性标题和侧边栏

链表中的连续动态内存分配