繁体   English   中英

根据div行数减少字体大小

[英]Reduce font-size based on number of div lines

如标题所示,我希望根据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();
}

您要查找的大小是相对于字体系列的,因为如果在同一文本中使用不同字体测试行号,则行号不一定总是相同。 使用以下解决方案:

如何计算DOM元素内的文本行? 我可以吗?

考虑到最大行数,这是一个近似解决方案

 <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