Fit text perfectly inside a div (height and width) without affecting the size of the div

前端 未结 9 1849
盖世英雄少女心
盖世英雄少女心 2020-12-02 17:07

I apologise in advance as I know this question has come up many times before but I just can\'t seem to find the right solution (and believe me I\'ve tried a few!)

Ba

9条回答
  •  醉酒成梦
    2020-12-02 18:02

    Here's a slightly modified version of the given answers.

    Requirements :

    1. The class containing text has the "resize" class.
    2. it contains height and width (%, px, whatever...)

    What changes in this version ?

    1. I added resizing ( by binding the event resize to the function) autoSizeText. This is far from ideal, but if we don't resize a lot, it should be ok.
    2. In previous versions, text is only getting smaller. Now it tries to find the biggest font without going outside the div.

    Note:

    I don't claim the code is production ready. But if you find something you can enhance, please share it with the community.

    var autoSizeText = function () {
        var el, elements, _i, _len;
        elements = $('.resize');
        if (elements.length < 0) {
            return;
        }
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
            el = elements[_i];
            dichoFit = function (el) {
    
                diminishText = function () {
                    var elNewFontSize;
                    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
    
                    return $(el).css('font-size', elNewFontSize);
                };
                augmentText = function () {
                    var elNewFontSize;
                    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) + 1) + 'px';
    
                    return $(el).css('font-size', elNewFontSize);
                };
    
    
                diminishText();
                while (el.scrollHeight < el.offsetHeight) {
                    augmentText();
                }
                augmentText();
                while (el.scrollHeight > el.offsetHeight) {
                    diminishText();
                }
    
            }
            dichoFit(el);
        }
    };
    
    $(document).ready(function () {
        autoSizeText();
        $(window).resize(function resizeText(){
            autoSizeText()
        })
    });
    .sizable{
     width: 50vw;
     height: 50vh;
     border: 2px solid darkred;
    }
    
    
      
    I am a sizable div and I have explicit width and height.

提交回复
热议问题