这里有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;
更复杂的例子:
水平滚动相同。分配width
属性white-spase
后设置为正常。第一个块正好scrollWidth
,第二个块得到1个像素。
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;
答案 0 :(得分:2)
https://docs.oracle.com/cd/B10501_01/server.920/a90842/ch6.htm#1006369似乎对你有用:
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;
答案 1 :(得分:2)
返回270.078px。我认为这对你有用。
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;