可能重複:
Auto-size dynamic text to fill fixed size container計算文本字體大小來填充容器文字
如果容器包含只是沒有子元素的純文本,然後將下面的代碼是一個可行的解決方案:
(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>
,我們希望也能自動調整大小的孩子,保持相同的文字作爲高「正文」這是一個文本節點?兒童可能會有不同的字體系列或其他參數。
上面的算法如何才能得到這樣的結果?
@Diodeus - 不是重複!閱讀帖子並注意有關子元素的差異。 –