gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:54:32 25 4
gpt4 key购买 nike

这里有 2 个 block ,第一个 block 有点击处理程序,它将 block 的 scrollWidth 分配给它的 width 属性。没有填充或边框,但在分配属性时,一个单词换行到下一行。

据我所知,这是因为当 Web 检查器中可见的值为 270.08 时,scrollWidth 返回 270。如果我将 width 值设置为 270.08,该词将不会换行到下一行。

如何获取包含小数部分的内容的实际宽度?

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

第二次点击 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>

更复杂的例子:

与水平滚动相同。分配 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com