Javascript that automatically sets font-size on element so that text doesn't overflow? (autofit)

戏子无情 提交于 2019-12-06 12:07:22

问题


You know what I mean? Like let's say we have:

<div style="width:100px;font-size:10px">Some Text</div>

But then we could also possibly have a much longer text string in that div, in that case I would want that div to have font-size:7px or whatever, so that the whole string fits without overflowing.

I'm sure there's already something like this written, I wouldn't want to reinvent this. Preferably a jQuery plugin?

Any suggestions would be appreciated! Thanks


回答1:


Based on an answer proposed in Nick's question:

$(function() {
    $(".shrinkByWidth").each(function() {
        var targetWidth = $(this).parent(':first').width();

        if (isNaN(parseInt($(this).css("font-size"))))
            $(this).css("font-size", '24px');

        while ($(this).width() > targetWidth) 
        {
            $(this).css("font-size", (parseInt($(this).css("font-size")) - 1) + 'px');
        }
    });
});

Works great for me!



来源:https://stackoverflow.com/questions/1178651/javascript-that-automatically-sets-font-size-on-element-so-that-text-doesnt-ove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!