[英]d3 bar chart- How do I automatically change font-size of value so that it fits within bar
[英]Truncate/increase font size within a div so it fits
假设我有一个大小为100px x 20px
的div
,并且其中的文本随机设置不同的长度,即一些文本部分很长而一些很短。
因此,当文本量较少时,div内有空格。 如果有大量文本,它会溢出。
如果文本小于div
容量,那么该文本的font-size
将最大化以尽可能地适应该div
,而不会剪切/剪切 。
但是如果文本大小大于div
容量,那么我想截断文本并追加...
(仅限3个点)。
对于第一部分,我建议将文本包装在<span>
以便可以获取其offsetWidth
,然后可以将其font-size
样式属性设置为200 / span.offsetWidth
。 但请记住,这是一个粗略的计算,有一些近似值,也许你想用190或195而不是200做得更好。
对于第二部分,只需设置overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
。 请记住,省略号的点不会出现在较旧的Firefox客户端中。
我想你需要另一个(内部) <div>
才能检查文本的高度。
<div id="mainDiv">
<div class="inner">
<p>Some text</p>
</div>
</div>
//css
#mainDiv
{
width: 200px;
height: 50px;
overflow: hidden;
}
然后你需要一些简单的函数(像这样):
//pseudocode
function doCheck()
{
if (".inner".height > "#mainDiv".height) truncate()
else increaseSize()
}
function truncate()
{
for (i = 1; i <= ".inner".wordCount)
while (".inner".height <= "#mainDiv".height)
{
addOneMoreWord() + " …";
if (".inner".height > "#mainDiv".height) removeLastWord()
}
}
//similar thing for increaseSize();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.