0

好的,我有这个代码。

<script>
$(document).ready(function(){

    var totalWidth = 0;

    $('.thewidgets').each(function(index) {
        totalWidth += parseInt($(this).width(), 10);
    });

    $('#marginwidgets').css({width: totalWidth});

});
</script>

html

<div id="marginwidgets">
 <div class="thewidgets">
  the widgets 1
 </div>
 <div class="thewidgets">
  the widgets 2
 </div>
 <div class="thewidgets">
  the widgets 3
 </div>
</div>

和CSS

#marginwidgets
{
margin: 0px auto;
overflow: auto;
max-width: 100%;
}
.thewidgets
{
width: 284px
padding: 5px;
margin-left: 10px;
}
.thewidgets:first-child
{
margin-left: 0px !important;
}

正如您在脚本中看到的,例程是获取 .thewidgets 的总宽度,然后将其总宽度应用到 #marginwidgets 中,这应该可以完美地集中 #marginwidgets。

但我希望 .thewidgets 的总宽度包括边距和填充,然后将其应用到#marginwidgets 但我不知道如何制作它,这里有人可以弄清楚该怎么做吗?

4

1 回答 1

3

使用outerWidth而不是宽度,并true作为参数传递以包含边距:

$(this).outerWidth(true);

此外,维度函数返回数字而不是字符串,因此parseInt尽管您可能想使用Math.floor,Math.ceil或,但没有必要Math.round

于 2012-10-12T01:50:38.457 回答