11

offsetWidth isn't good enough for me right now, as this includes padding and border width. I want to find out the content width of the element. Is there a property for that, or do I have to take the offsetWidth and then subtract the padding and border width from the computed style?

4

4 回答 4

13

由于这在谷歌搜索时首先出现但还没有合适的答案,所以这里有一个:

function getContentWidth (element) {
  var styles = getComputedStyle(element)

  return element.clientWidth
    - parseFloat(styles.paddingLeft)
    - parseFloat(styles.paddingRight)
}

基本上,我们首先获取元素的宽度,包括填充 ( clientWidth),然后减去左右填充。我们需要parseFloat填充,因为它们以px- 后缀字符串的形式出现。


我在CodePen上为此创建了一个小操场,看看吧!

于 2017-11-10T13:42:42.830 回答
2

我会建议scrollWidthclientWidth取决于您是否要考虑滚动条。

查看确定元素的尺寸规范本身

于 2013-07-03T00:56:06.570 回答
2

听起来你想getComputedStyle在元素上使用。你可以在这里看到一个getComputedStylevs.的例子:http offsetWidth: //jsbin.com/avedut/2/edit

或者:

window.getComputedStyle(document.getElementById('your-element')).width;
于 2013-07-03T00:59:33.310 回答
0

我有类似的问题,我的父元素不是窗口或文档...我正在通过 Javascript 加载图像并希望它在加载后居中。

var parent = document.getElementById('yourparentid');
var image = document.getElementById('yourimageid');
image.addEventListener('load'),function() {
    parent.scrollBy((image.width-parent.clientWidth)/2,(image.height-parent.clientHeight)/2);
}

每当您设置 src 时,它都会滚动到图像的中心。这对我来说是在放大图像的高分辨率版本的背景下。

于 2021-02-04T02:26:28.853 回答