自动调整动态文本大小以填充固定大小的容器 [英] Auto-size dynamic text to fill fixed size container

查看:224
本文介绍了自动调整动态文本大小以填充固定大小的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将用户输入的文本显示为固定大小的div。我想要的是自动调整字体大小,以便文本尽可能多地填充框。

I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.

所以 - 如果div是400px x 300px。如果有人输入ABC,那么它真的很大的字体。如果他们输入一个段落,那么它将是一个小字体。

So - If the div is 400px x 300px. If someone enters ABC then it's really big font. If they enter a paragraph, then it would be a tiny font.

我可能想开始一个最大字体大小 - 也许32px,而文本太大,不适合容器,收缩字体大小,直到它适合。

I'd probably want to start with a maximum font size - maybe 32px, and while the text is too big to fit the container, shrink the font size until it fits.

推荐答案

感谢 Aackack 。我想使用jQuery。

Thanks Attack. I wanted to use jQuery.

您指向正确的方向,这是我结束了:

You pointed me in the right direction, and this is what I ended up with:

链接到插件: https://plugins.jquery.com/textfill/

和源的链接: http://jquery-textfill.github.io/

;(function($) {
    $.fn.textfill = function(options) {
        var fontSize = options.maxFontPixels;
        var ourText = $('span:visible:first', this);
        var maxHeight = $(this).height();
        var maxWidth = $(this).width();
        var textHeight;
        var textWidth;
        do {
            ourText.css('font-size', fontSize);
            textHeight = ourText.height();
            textWidth = ourText.width();
            fontSize = fontSize - 1;
        } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
        return this;
    }
})(jQuery);

$(document).ready(function() {
    $('.jtextfill').textfill({ maxFontPixels: 36 });
});

,我的html如下

<div class='jtextfill' style='width:100px;height:50px;'>
    <span>My Text Here</span>
</div>

这是我的第一个jQuery插件,所以它可能不如它应该是。当然欢迎指针。

This is my first jquery plugin, so it's probably not as good as it should be. Pointers are certainly welcome.

这篇关于自动调整动态文本大小以填充固定大小的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆