koj*_*ow7 11 javascript reactjs
我正在使用flexbox布局,并尝试在特定div中获取文本以进行调整以适合该div。
因此,例如,如果我有如下代码:
<div style={{display: "flex"}}>
<div style={{flex: 1}}>
A really, really, really, really long phrase here that will fit this div, and may wrap onto multiple lines if necessary. In this case it should fill half of the available space as the other div will cover the other half of the space.
</div>
<div style={{flex: 1}}>
Some other text
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
实际上,文本将从数据库中提取,因此长度是动态的。
如何在第一个div中获取文本以自动调整以适合整个div?
说明: div应该保持固定大小,并且只有文本应该缩小以适合div,而不是使div溢出。
更新资料
我还发布了一个关于特定模块的更具体的问题,该模块称为react-textfit无法按我期望的方式工作。
这是一些应该满足您要求的代码。
let size_div = document.querySelector("#font_size");
let div = document.querySelector("#fixed");
while (div.scrollHeight > div.clientHeight) {
let style = window.getComputedStyle(div, null).getPropertyValue('font-size');
let fontSize = parseFloat(style);
if (fontSize <= 1) {
break;
}
div.style.fontSize = "" + (fontSize - 1) + "px";
size_div.innerHTML = " " + div.style.fontSize;
}
Run Code Online (Sandbox Code Playgroud)
您可以在这里尝试一下: https: //codepen.io/lowtex/pen/xNawEO
我不是 ReactJs 用户,但我使用过 CSS Flex
您可以将容器的高度设置为自动,以便它在我们获取内容时发生变化。另外,您应该在 css 中设置 min-height 和max-height属性,以便如果内容小于给定长度,它会出现min-height,如果内容太大,它不会超过给定的容器高度。
为了禁止内容开箱即用,您可以使用overflow:hidden. 这将防止内容脱离盒子。
希望这对您想要如何继续进行有所帮助。