Jquery - 将文本匹配到元素中,只有lettersspacing&字间距

时间:2013-04-15 13:07:07

标签: jquery font-size justify letter-spacing word-spacing

有插件吗?我一直在筛选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;
}

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

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

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

            }

          });
        }

结果:   enter image description here

1 个答案:

答案 0 :(得分:1)

我自己编写了一个脚本,然后开始使用刻字将每个字母彼此分开,然后计算出它们合在一起的空间。

Lettering.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'});
        }
    };
}