最大文本大小可能在div [英] Largest text size possible inside div

查看:97
本文介绍了最大文本大小可能在div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来自动调整div内的文本到其最大大小。

I'm looking for a way to autoresize the text inside a div to its maximum size. The maximum size is the biggest size possible while still fitting the div.

我知道这是不可能在CSS中做到这一点。是否可以使用javascript?

I know it's not possible to do this in CSS. Is it possible with the use of javascript?

推荐答案

您可以使用纯JavaScript中的这种技巧来自动调整字体大小:

You can use such trick in pure JavaScript to "auto resize" the font size:

window.onload = function() {
    var oDiv = document.getElementById("Div1");
    oDiv.style.overflow = "auto"; //for Firefox, but won't ruin for other browsers
    var fontSize = 14;
    var changes = 0;
    var blnSuccess = true;
    while (oDiv.scrollWidth <= oDiv.clientWidth) {
        oDiv.style.fontSize = fontSize + "px";
        fontSize++;
        changes++;
        if (changes > 500) {
            //failsafe..
            blnSuccess = false;
            break;
        }
    }
    if (changes > 0) {
        //upon failure, revert to original font size:
        if (blnSuccess)
            fontSize -= 2;
        else
            fontSize -= changes;
        oDiv.style.fontSize = fontSize + "px";
    }
};

现场测试用例

< div> 如果你知道它,否则最好使用较小的数字作为第一个数字。

Start with the actual font size of the <div> if you know it, otherwise better use smaller number as the first number.

上面的代码工作原理是当文本大于其容器,那么实际宽度的 scrollWidth 属性将大于设置的宽度。

The above code works on the principle that when the text is bigger than the set width of its container, the scrollWidth property which is the "actual" width will be bigger than the set width.

Edit:如果 overflow CSS属性设置为,则Firefox不会更新 scrollWidth 默认可见值,因此您必须将其设置为自动 - 代码是为您做的,但也可以通过CSS设置它,如果你喜欢。

Firefox won't update the scrollWidth property if the overflow CSS property is set to its default "visible" value, so you must set it to "auto" - the code is doing it for you, but also possible setting it via CSS if you prefer.

这篇关于最大文本大小可能在div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆