简体   繁体   English

根据长度和容器大小动态调整文本大小

[英]Dynamically resize text based on length and container size

How do I resize some text based on the length of the text and the size of the container? 如何根据文本的长度和容器的大小调整某些文本的大小?

It's for a title. 这是一个标题。 I basically want to say: "If the dynamically generated <h2> has less than 10 characters, increase the font size to 2em to fill the space. Otherwise, leave it at 1em ". 我基本上想说:“如果动态生成的<h2>少于10个字符,则将字体大小增加到2em以填充空间。否则,将其保留为1em ”。

Ideally I'd quite like to just resize the text up to a maximum. 理想情况下,我只想将文本的大小调整到最大。 As in, "the title isn't fully fitting the horizontal space, so increase font size without going onto a second line". 就像“标题不完全适合水平空间,因此增加字体大小而不用移至第二行”。 Is that doable? 那可行吗?

I can't send you a link, since the site isn't live. 由于该网站未启用,因此我无法向您发送链接。

If you have a fixed-sized container one technique you can use is to detect whether the text is overflowing its container, then reduce the font size until it is no longer overflowing. 如果您有固定大小的容器,则可以使用的一种技术是检测文本是否在其容器中溢出,然后减小字体大小,直到不再溢出为止。 This way you always get the best fit without counting characters. 这样一来,您始终可以获得最佳的贴合度而无需计算字符。 With proportional fonts, counting characters won't always work. 使用比例字体时,对字符进行计数并不总是有效。

The technique for detecting overflow is described here: 这里描述了检测溢出的技术:

detect elements overflow using jquery 使用jQuery检测元素溢出

Also checkout Fittext.js . 还要签出Fittext.js You can look at the source what it does - which is tiny. 您可以查看源代码的作用-很小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM