正如Mark所说,text-align:justify;是最简单的解决方案。但是,对于短文本,它不会有任何效果。以下jQuery代码将文本伸展到容器的宽度。
它计算每个字符的空间并相应地设置字母间距,以便文本延伸到容器的宽度。
如果文本太长,不适合容器,它允许它展开到下一行和设置text-align:justify;到文本。
这里是一个演示:
$.fn.strech_text = function(){
var elmt = $(this),
cont_width = elmt.width(),
txt = elmt.html(),
one_line = $('' + txt + ''),
nb_char = elmt.text().length,
spacing = cont_width/nb_char,
txt_width;
elmt.html(one_line);
txt_width = one_line.width();
if (txt_width < cont_width){
var char_width = txt_width/nb_char,
ltr_spacing = spacing - char_width + (spacing - char_width)/nb_char ;
one_line.css({'letter-spacing': ltr_spacing});
} else {
one_line.contents().unwrap();
elmt.addClass('justify');
}
};
$(document).ready(function () {
$('.stretch').each(function(){
$(this).strech_text();
});
});
p { width:300px; padding: 10px 0;background:gold;}
a{text-decoration:none;}
.stretch_it{ white-space: nowrap; }
.justify{ text-align:justify; }
.one{font-size:10px;}
.two{font-size:20px;}
.three{font-size:30px;}
.four{font-size:40px;}
.arial{font-family:arial;}
Stretch me
Stretch me
Stretch link
I am too slong, an I would look ugly if I was displayed on one line so let me expand to several lines and justify me.
Stretch me
Stretch me
Stretch me
Don't stretch me