Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

css - Calculate total width of Children with jQuery

I've tried finding an understandable answer to this, but given up.

In order to have dymnamic content (like blog posts and images) in a horizontal website (like on thehorizontalway.com) you must set a fixed width for the BODY in pixles, right? Because you use floated elements inside it that otherwise would break and wrap down the page, depending on the browsers width.

EDIT! This specific value can be calculated with jQuery, thanks for that :) In this example, an additional value is added to the total size, which can be used for content before the floated elements. Now the body gets a dynamic width!

My initial thought was to have jQuery calculate this for us: ( 'EACH POSTS WIDTH' * 'NUMBER OF POSTS' ) + 250 (for the extra content)

HTML code

<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 -->

The result and answer from Alconja

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

Thanks so much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looks like you've got it pretty much right... a couple of notes though:

  • .outerWidth(true) includes the padding & margin (since you're passing true), so there's no need to try & add that in again.
  • .outerWidth(...) only returns the width of the first element, so if each element is a different size, multiplying this by the number of posts won't be an accurate value of total width.

With that in mind something like this should give you what you're after (keeping your 250 initial padding, which I assume is for menus & things?):

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

Does that help, or is there some other specific problem you're having (wasn't quite clear from your question)?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...