javascript - 获取指定元素的总宽度,包括边距和填充

标签 javascript jquery css

好的,我有这个代码。

<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 中,但我不知道如何制作它,请问这里有人能弄清楚该怎么做吗?

最佳答案

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

$(this).outerWidth(true);

此外,维度函数返回数字而不是字符串,因此 parseInt 不是必需的,尽管您可能想使用 Math.floorMath.ceilMath.round

关于javascript - 获取指定元素的总宽度,包括边距和填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851118/

相关文章:

javascript - 根据显示的复选框显示警报

javascript - 如何隐藏文本并在点击时显示

javascript - 在 html5 本地存储中存储音频文件 - 使用 javascript 下载音频文件

javascript - ngAnimate 与 ui-view

javascript - 如何使用填充属性数据传输创建事件?

javascript - 当我们隐藏/显示 ui-grid 中的列时会触发哪个事件?

javascript - 通过代理服务器发出 jQuery.ajax 请求

javascript - 捕获页面加载后创建的 <img> 标签的 img 加载错误(例如通过 AJAX)

html - 位置 :fixed does not work on android

css - 纯 CSS 中的第一类和最后一类选择器