根据包装的内容获取和设置包装宽度

Get and set wrapper width based on its content

本文关键字:包装 设置 获取      更新时间:2023-09-26

我有以下设置:

<div id="wrapper">
    <div class="column1"></div>
    <div class="column3"></div>
    <div class="column2"></div>
</div>
#wrapper {
    position:absolute;
}

每个"列"都有不同的宽度和一个float: left。所以这3列加在一起是,比方说,900像素宽;但如果我放入一个新列,我希望包装器能自动获得它。

因此,我想使用JavaScript根据包装器包含的列来获取和设置包装器的宽度。

$("#wrapper").width(function() {
    var width = 0;
    $(this).children('[class^="column"]').each(function() {
        width += $(this).width();
    });
    return width;
});​

不使用浮点,而是使用display:inline-block(Demo)

var w = 0;
$('#wrapper > div').each(function(index) {
  w += $(this).outerWidth();
});
$('#wrapper').width(w);

这是一把小提琴:http://jsfiddle.net/BramVanroy/sYMLr/

var totalWidth = 0;
$("div#wrapper > div").each(function(index) {
    totalWidth += parseInt($(this).outerWidth(true), 10);
});
$("div#wrapper").width(totalWidth);​