2012-10-12 42 views
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中,但我不知道如何制作它,请问有人可以找出它该怎么做吗?

+1

'totalWidth + = $(this).outerWidth(true);'不需要parseInt,我们知道它返回的是什么。 – Ohgodwhy

+0

谢谢..作品像魅力 –

回答

3

使用outerWidth,而不是宽度,并通过true作为参数传递给包括边距:

$(this).outerWidth(true); 

而且尺寸函数返回的数字,而不是字符串,这样parseInt心不是必要的,虽然你可能想使用Math.floorMath.ceilMath.round

+0

谢谢,作品像魅力 –

相关问题