0

有这个插件吗?我一直在筛选 internetz 并发现 bigText、Justify、fitText、textFit 但它们似乎都适用于我不想做的字体大小。我只希望文本适合具有定义宽度的元素。

HTML:

<div id="title">
   <h1>One header that i pretty long</h1>
   <h2>Sub-header that is shorter</h2>
</div>

CSS:

#title {
   width: 300px;
}

h1 {
   font-size: 3em;
}

h2 {
   font-size: 2em;
}

到目前为止,我发现的插件的问题是子标题最终会更大,因为它的字母数量更少。

我找到了这个解决方案,但问题是它给了我一个稍微不平衡的间距,证明

JS

if(config.fonts_loaded){
            $(".title .justify").each(function(i, e) {
            var $t    = $(this);
            console.log($t.height());
            var text  = $t.text();
            var tLen  = text.length -1;
            var i     = 0;
            var letter;
            var ratio;
            //  We have the data we need to rebuild text. Lose original text.
            //
            $t.empty();
            while(i <= tLen) {
              letter = $("<span></span>")
              .css({
                "position" : "absolute"
              })
              .text(text.charAt(i));
              $t.append(letter);
              ratio = i / tLen;
              //  Place each character in its rational slot, retreating margin

              //  so as to stay within bounds (last character starts at 100% of width).

              //

              letter.css({

                "left"      : (100 * ratio) + "%",

                "margin-left" : -letter.width() * ratio

              });

              ++i

            }

          });
        }

结果是: 在此处输入图像描述

4

1 回答 1

1

而是自己制作了一个脚本,并从字母开始将每个字母彼此分开,然后计算出它们占用了多少空间。

刻字.js

这是我的最终代码,

function letter_space_me(element){
    var el = $(element).text();
    el = el.replace(/ /g, '&nbsp;'); // REPLACE ALL WHITESPACES WITH &NBSP;
    $(element).html(el);
    $(element).lettering();
    var characters = $(element + ' span');
    var number_of_chars = characters.length;
    var parent_width = $(element).parent().width()

    var total_width = 0;

    for (var i = 0; i < characters.length; i++) {
        total_width += $(characters[i]).width();
    };

    var spacing = (parent_width - total_width) / (number_of_chars - 1); // GET SPACING PER CHARACTERS EXCEPT FOR THE LAST CHARACTER WHICH WE DONT WANT TO GIVE AND SPACE TO.

    for (var i = 0; i < characters.length; i++) {
        if((characters.length - i) > 1){
            $(characters[i]).css({'padding-right' : spacing + 'px'});
        }
    };
}
于 2013-04-15T14:34:49.760 回答