简体   繁体   English

根据div行数减少字体大小

[英]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. 如标题所示,我希望根据div中的行数和起始大小来减少字体。 (Each line reduces the font) . (每行减少字体)

The function below is all I have and works based on the height of the div. 下面的函数是我所拥有的,并且根据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? 如何计算DOM元素内的文本行? 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> 

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

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