代码之家  ›  专栏  ›  技术社区  ›  elundmark

使用jQuery计算子项的总宽度

  •  17
  • elundmark  · 技术社区  · 17 年前

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

    动态的 网站中的内容(如博客文章和图片) 横向网站 thehorizontalway.com )你必须用皮克斯为身体设定一个固定的宽度,对吗? 因为您在其中使用了浮动元素,否则会根据浏览器的宽度分解和包装页面。

    编辑 此特定值可以是 具有 jQuery

    我最初的想法是让jQuery为我们计算:

    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);
    });
    

    非常感谢!

    2 回复  |  直到 17 年前
        1
  •  37
  •   472084    14 年前

    看起来你说得很对。。。不过有几个注意事项:

    • .outerWidth(true) 包括填充和;保证金(因为你通过了 true ),因此没有必要尝试&再加一次。
    • .outerWidth(...) 只返回第一个元素的宽度,因此如果每个元素的大小不同,那么将其乘以帖子的数量将不是总宽度的准确值。

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

    这有帮助吗,或者你还有其他一些具体的问题(你的问题不太清楚)?

        2
  •  0
  •   smac89    10 年前

    你可以用这一条线来计算宽度,虽然比我想要的要长一点。

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