这里有 2 个 block ,其中第一个具有点击处理程序,它将 block 的 scrollWidth
分配给它的 width
属性。没有填充或边框,但分配属性时,一个单词会换行到下一行。
据我了解,发生这种情况是因为当 Web 检查器中可见的值为 270.08
时,scrollWidth
返回 270
。如果我将 width
值设置为 270.08
,该单词将不会换行到下一行。
如何获得内容的真实宽度(包括小数部分)?
顺便说一句,getComputedStyle(...).width
返回"270.078px"
,但此方法不适合 block 溢出的情况。我需要内容的大小。
第二次点击 div 会将宽度
设置为其计算值。
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>
更复杂的示例:
与水平滚动相同。分配 width
属性后,white-spase
设置为正常。第一个 block 精确地获得了 scrollWidth
,第二个 block 获得了 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';
});
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;
}
<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>
最佳答案
Element.getBoundingClientRect()似乎对你有用:
document.querySelector('p').addEventListener('click', function (event) {
var width = this.getBoundingClientRect().width;
console.log(width);
this.style.width = width + 'px';
});
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>
关于javascript - 如何获取div的正确内容大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517229/