如何获得div的正确内容大小?

时间:2016-11-09 22:43:21

标签: javascript html css

这里有2个区块,其中第一个区块有点击处理程序,可以将scrollWidth块分配给它的width属性。没有填充或边框,但是当分配属性时,一个单词将被包装到下一行。

据我了解,因为scrollWidth返回270,因此在网络检查器中显示的值为270.08时会发生这种情况。如果我将width值设置为270.08,则该单词将被包裹到下一行。

如何获得真实的内容宽度,包括小数部分?

顺便说一下,getComputedStyle(...).width返回"270.078px",但是如果块有溢出,则此方法不适用。我需要内容的大小。

第二次点击div会将width设置为它的计算值。

https://jsfiddle.net/0dqzvw4r/



document.querySelector('p').addEventListener('click', function first(event) {
  var width = this.scrollWidth;
  var real = getComputedStyle(this).width;
  
  console.log(width);
  console.log(real);
  
  this.style.width = width + 'px';
  
  this.removeEventListener('click', first);
  this.addEventListener('click', function (event) {
    this.style.width = real;
  });
});

body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
}

<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>
&#13;
&#13;
&#13;

更复杂的例子:

水平滚动相同。分配width属性white-spase后设置为正常。第一个块正好scrollWidth,第二个块得到1个像素。

&#13;
&#13;
document.querySelector('p').addEventListener('click', function (event) {
  var width = this.scrollWidth;
  console.log(width);
  this.style.width = width + 'px';
  this.nextElementSibling.style.width = width + 1 + 'px';
});
&#13;
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
  width: 10em;
  white-space: nowrap;
  overflow: auto;
}

p[style] {
  white-space: normal;
}
&#13;
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

https://docs.oracle.com/cd/B10501_01/server.920/a90842/ch6.htm#1006369似乎对你有用:

&#13;
&#13;
document.querySelector('p').addEventListener('click', function (event) {
  var width = this.getBoundingClientRect().width;
  console.log(width);
  this.style.width = width + 'px';
});
&#13;
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
}
&#13;
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

返回270.078px。我认为这对你有用。

&#13;
&#13;
document.querySelector('p').addEventListener('click', function (event) {
  var width = window.getComputedStyle(this).width;
  console.log(width);
  this.style.width = width + 'px';
  
});
&#13;
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
}
&#13;
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>
&#13;
&#13;
&#13;