简体   繁体   中英

Reduce font-size based on number of div lines

As the title says, I wanted the font to be reduced based on the number of lines in the div and from a start size. (Each line reduces the font) .

The function below is all I have and works based on the height of the div.

$.fn.resizeText = function (options) {  

    var settings = $.extend({ maxfont: 40, minfont: 17 }, options);

    var style = $('<style>').html('.nodelays ' +
    '{ ' +
        '-moz-transition: none !important; ' +
        '-webkit-transition: none !important;' +
        '-o-transition: none !important; ' +
        'transition: none !important;' +
    '}');

    function shrink(el, fontsize, minfontsize)
    {
        if (fontsize < minfontsize) return;

        el.style.fontSize = fontsize + 'px';            

        if (el.scrollHeight > el.closest(".container").offsetHeight) shrink(el, fontsize - 1, minfontsize);
    }

    $('head').append(style);

    $(this).each(function(index, el)
    {
        var element = $(el);

        element.addClass('nodelays');

        shrink(el, settings.maxfont, settings.minfont);

        element.removeClass('nodelays');
    });

    style.remove();
}

The size you are looking for is relative to the font family, because it is not always the same number of lines if they are tested with different fonts in the same text. using the following solution:

How can I count text lines inside an DOM element? Can I?

This is an approximate solution, taking into account a maximum number of lines

 <body> <div id="content" style="width: 80px; font-size: 20px; line-height: 20px; visibility: hidden;"> hello how are you? hello how are you? hello how are you? hello how are you? how are you? how are you? how are you? </div> <script> function countLines(elm) { var el = document.getElementById(elm); var divHeight = el.offsetHeight; var lineHeight = parseInt(el.style.lineHeight); var lines = divHeight / lineHeight; return lines; } var max_lines = 10; function auto_size_text(elm) { var el = document.getElementById(elm); var lines = countLines(elm); var size = parseInt(el.style.fontSize.replace("px", "")); if(lines > max_lines) { size--; el.style.fontSize = size + "px"; el.style.lineHeight = size + "px"; auto_size_text(elm); } } function show_div (elm) { var el = document.getElementById(elm); el.style.visibility = ""; } auto_size_text("content"); show_div("content"); </script> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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