0

我需要使我的每个<p>字体都具有固定宽度和高度的灵活字体大小。

当前代码

CSS

p{
    width:500px;
    height:100px;
    background-color:#F0F0F0;
    margin:10px;
    padding:5px;
    font-size:24px;
}

HTML

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.</p>
<br><br><br>
<br><br><br>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros, faucibus sit amet aliquet ac, varius id eros.</p>
<br><br><br>

<!-- This one is perfect -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.</p>

检查并尝试 jsfiddle 中的代码

http://jsfiddle.net/8GNAV/

这是我想要达到的输出

http://jsfiddle.net/8GNAV/1/

4

1 回答 1

2

总体思路是获取overflow:hidden,然后不断缩小文本,直到scrollHeight小于offsetHeight。像这样:

[].forEach.call(document.getElementsByTagName('p'),function(p) {
  p.style.overflow = "hidden";
  var f = 24;
  while(f > 6 && p.scrollHeight > p.offsetHeight) {
    f--;
    p.style.fontSize = f+"px";
  }
});

演示

于 2013-06-20T17:44:44.273 回答