【发布时间】:2012-10-01 00:31:12
【问题描述】:
如果容器只包含一个没有子元素的纯文本,那么下面的代码是一个可行的解决方案:
(function($) {
$.fn.textfill = function(options) {
return this.each(function() {
var text = $(this).text();
$(this).text('');
var container = $('<span />').text(text).appendTo($(this));
var min = 1, max = 200, fontSize;
do {
fontSize = (max + min) / 2;
container.css('fontSize', fontSize);
var multiplier = $(this).height()/container.height();
if (multiplier == 1) { min = max = fontSize}
if (multiplier > 1) { min = fontSize}
if (multiplier < 1) { max = fontSize}
} while ((max - min) > 1);
fontSize = min;
if ($(this).width() < container.width()) {
min = 1;
do {
fontSize = (max + min) / 2;
container.css('fontSize', fontSize);
var multiplier = $(this).width()/container.width();
if (multiplier == 1) { min = max = fontSize}
if (multiplier > 1) { min = fontSize}
if (multiplier < 1) { max = fontSize}
} while ((max - min) > 1);
fontSize = min;
}
container.remove();
$(this).text(text);
var minFontSize = options.minFontPixels;
var maxFontSize = options.maxFontPixels;
$(this).css('fontSize',
minFontSize && (minFontSize > fontSize) ?
minFontSize :
maxFontSize && (maxFontSize < fontSize) ?
maxFontSize :
fontSize);
});
};
})(jQuery);
查看演示here。
但是如果容器中包含子元素呢:
<div><span class="c1">text1</span>main text<span class="c2">text2</span></div>
我们还想自动调整孩子的大小,让文本与作为文本节点的“主文本”保持相同的高度?儿童可能有不同的 font-family 或其他参数。
如何改进上述算法以获得这样的结果?
【问题讨论】:
-
@Diodeus - 不是重复的!阅读关于子元素的帖子和通知差异。
标签: javascript jquery