繁体   English   中英

如何将font-size设置为div大小的100%?

[英]How to set the font-size to 100% the size of a div?

我有一个静态尺寸的div。 有时,比div长的文本将被放置在那里。 无论如何,是否通过JavaScript就能始终实现适合div宽度的文本? 我知道有jQuery修复程序,但在这种情况下需要纯JS解决方案。

即使您有指向演示/教程的链接也可能会有所帮助,谢谢。

到这里,这应该做您想要的: JSFiddle

基本上,这里的关键是对照output.height检查output.scrollHeight 请考虑以下设置:

HTML:

<button onclick="addText(); resizeFont()">Click Me to Add Some Text!</button>
<div id="output"></div>

CSS:

div {
    width: 160px;
    height: 160px;
}

这将创建一个Square div,并通过addText()方法将其随机长字符串填充。

function addText() {
    var text   = "Lorem ipsum dolor amit",
        len    = Math.floor(Math.random() * 15),
        output = document.querySelector('#output'),
        str    = [];
    for (; --len;)
        str.push(text);

    output.innerHTML = str.join(', ');
}

魔术在于resizeFont()函数。 基本上,这样做是在添加文本之后,将divfontSize设置为其自己的高度。 这是当您具有1个字符的字符串(即fontSize将等于高度)时的基本情况。 随着字符串长度的增加,需要将fontSize减小,直到scrollHeight等于div的高度。

function resizeFont() {
    var output   = document.querySelector('#output'),
        numRE    = /(\d+)px/,
        height   = numRE.exec(window.getComputedStyle(output).height)[1],
        fontSize = height;

    // allow div to be empty without entering infinite loop
    if (!output.innerHTML.length) return;

    // set the initial font size to the height of the div
    output.style.fontSize = fontSize + 'px';

    // decrease the font size until the scrollHeight == height
    while (output.scrollHeight > height)
      output.style.fontSize = --fontSize + 'px';
}

关于此方法的好处是,您可以轻松地将事件侦听器附加到窗口的resize事件,使文本随着用户更改窗口大小而动态地调整大小: http : //jsfiddle.net/QvDy8/2/

window.onload = function() {
  window.addEventListener('resize', resizeFont, false);
}

暂无
暂无

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

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