Calculate total width of Children with jQuery

后端 未结 2 1280
北荒
北荒 2020-12-05 08:09

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 hori

相关标签:
2条回答
  • 2020-12-05 08:55

    You can calculate the width with this one-liner, albeit a tad longer than I would have liked.

    var width = $('.post').map(function(undefined, elem) {
        return $(elem).outerWidth(true);
    }).toArray().reduce(function(prev, curr) {
        return prev + curr;
    }, 0);
    
    0 讨论(0)
  • 2020-12-05 08:59

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

    0 讨论(0)
提交回复
热议问题