本文翻译自:Auto-size dynamic text to fill fixed size container
I need to display user entered text into a fixed size div. 我需要将用户输入的文本显示为固定大小的div。 What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible. 我想要的是自动调整字体大小,以使文本尽可能多地填充框中。
So - If the div is 400px x 300px. 所以-如果div为400px x 300px。 If someone enters ABC then it's really big font. 如果有人输入ABC,那么它确实是大字体。 If they enter a paragraph, then it would be a tiny font. 如果他们输入一个段落,那么它将是很小的字体。
I'd probably want to start with a maximum font size - maybe 32px, and while the text is too big to fit the container, shrink the font size until it fits. 我可能想从最大字体大小开始-也许是32px,并且当文本太大而无法容纳容器时,请缩小字体大小直到适合为止。
#1楼
参考:https://stackoom.com/question/2syk/自动调整动态文本大小以填充固定大小的容器
#2楼
Here is a version of the accepted answer which can also take a minFontSize parameter. 这是已接受答案的版本,也可以采用minFontSize参数。
(function($) {
/**
* Resizes an inner element's font so that the inner element completely fills the outer element.
* @author Russ Painter WebDesign@GeekyMonkey.com
* @author Blake Robertson
* @version 0.2 -- Modified it so a min font parameter can be specified.
*
* @param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
* @return All outer elements processed
* @example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
*/
$.fn.textfill = function(options) {
var defaults = {
maxFontPixels: 40,
minFontPixels: 10,
innerTag: 'span'
};
var Opts = jQuery.extend(defaults, options);
return this.each(function() {
var fontSize = Opts.maxFontPixels;
var ourText = $(Opts.innerTag + ':visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > Opts.minFontPixels);
});
};
})(jQuery);
#3楼
I forked the script above from Marcus Ekwall: https://gist.github.com/3945316 and tweaked it to my preferences, it now fires when the window is resized, so that the child always fits its container. 我从Marcus Ekwall分叉了上面的脚本: https ://gist.github.com/3945316并根据我的喜好对其进行了调整,现在在调整窗口大小时会触发它,以便孩子始终适合其容器。 I've pasted the script below for reference. 我已将以下脚本粘贴以供参考。
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this);
function resizefont(){
var parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier));
ourText.css("fontSize", maxFontSize > 0 && newSize > maxFontSize ? maxFontSize : newSize );
}
$(window).resize(function(){
resizefont();
});
resizefont();
});
};
})(jQuery);
#4楼
This is based on what GeekyMonkey posted above, with some modifications. 这基于上面发布的GeekyMonkey,并进行了一些修改。
; (function($) {
/**
* Resize inner element to fit the outer element
* @author Some modifications by Sandstrom
* @author Code based on earlier works by Russ Painter (WebDesign@GeekyMonkey.com)
* @version 0.2
*/
$.fn.textfill = function(options) {
options = jQuery.extend({
maxFontSize: null,
minFontSize: 8,
step: 1
}, options);
return this.each(function() {
var innerElements = $(this).children(':visible'),
fontSize = options.maxFontSize || innerElements.css("font-size"), // use current font-size by default
maxHeight = $(this).height(),
maxWidth = $(this).width(),
innerHeight,
innerWidth;
do {
innerElements.css('font-size', fontSize);
// use the combined height of all children, eg. multiple <p> elements.
innerHeight = $.map(innerElements, function(e) {
return $(e).outerHeight();
}).reduce(function(p, c) {
return p + c;
}, 0);
innerWidth = innerElements.outerWidth(); // assumes that all inner elements have the same width
fontSize = fontSize - options.step;
} while ((innerHeight > maxHeight || innerWidth > maxWidth) && fontSize > options.minFontSize);
});
};
})(jQuery);
#5楼
Most of the other answers use a loop to reduce the font-size until it fits on the div, this is VERY slow since the page needs to re-render the element each time the font changes size. 其他大多数答案都使用循环来减小字体大小,直到适合div为止,这非常慢,因为每次字体更改大小时页面都需要重新渲染元素。 I eventually had to write my own algorithm to make it perform in a way that allowed me to update its contents periodically without freezing the user browser. 我最终不得不编写自己的算法,以使其能够以某种方式定期执行更新其内容,而不会冻结用户浏览器。 I added some other functionality (rotating text, adding padding) and packaged it as a jQuery plugin, you can get it at: 我添加了其他功能(旋转文本,添加填充)并将其打包为jQuery插件,您可以在以下位置获得它:
https://github.com/DanielHoffmann/jquery-bigtext https://github.com/DanielHoffmann/jquery-bigtext
simply call 只需致电
$("#text").bigText();
and it will fit nicely on your container. 它将很好地适合您的容器。
See it in action here: 在这里查看实际操作:
http://danielhoffmann.github.io/jquery-bigtext/ http://danielhoffmann.github.io/jquery-bigtext/
For now it has some limitations, the div must have a fixed height and width and it does not support wrapping text into multiple lines. 目前,它有一些限制,div必须具有固定的高度和宽度,并且不支持将文本换成多行。
I will work on getting an option to set the maximum font-size. 我将努力获得一个设置最大字体大小的选项。
Edit: I have found some more problems with the plugin, it does not handle other box-model besides the standard one and the div can't have margins or borders. 编辑:我发现该插件还有更多问题,除了标准插件之外,它不能处理其他盒子模型,并且div不能有边距或边框。 I will work on it. 我会努力的。
Edit2: I have now fixed those problems and limitations and added more options. Edit2:我现在解决了这些问题和限制,并添加了更多选项。 You can set maximum font-size and you can also choose to limit the font-size using either width, height or both. 您可以设置最大字体大小,也可以选择使用宽度,高度或同时使用这两者来限制字体大小。 I will work into accepting a max-width and max-height values in the wrapper element. 我将努力在wrapper元素中接受max-width和max-height值。
Edit3: I have updated the plugin to version 1.2.0. Edit3:我已经将插件更新为版本1.2.0。 Major cleanup on the code and new options (verticalAlign, horizontalAlign, textAlign) and support for inner elements inside the span tag (like line-breaks or font-awesome icons.) 对代码进行了重大清理,并添加了新选项(verticalAlign,horizontalAlign,textAlign),并支持span标记内的内部元素(如换行符或超棒的字体图标)。
#6楼
The proposed iterative solutions can be sped up dramatically on two fronts: 所提出的迭代解决方案可以在两个方面大大加快:
1) Multiply the font size by some constant, rather than adding or subtracting 1. 1)将字号乘以某个常数,而不是加或减1。
2) First, zero in using a course constant, say, double the size each loop. 2)首先,使用过程常数为零,例如,使每个循环的大小增加一倍。 Then, with a rough idea of where to start, do the same thing with a finer adjustment, say, multiply by 1.1. 然后,大致了解从何处开始,再做一次更精细的调整,例如乘以1.1。 While the perfectionist might want the exact integer pixel size of the ideal font, most observers don't notice the difference between 100 and 110 pixels. 尽管完美主义者可能想要理想字体的确切整数像素大小,但大多数观察者并不注意到100和110像素之间的差异。 If you are a perfectionist, then repeat a third time with an even finer adjustment. 如果您是完美主义者,则可以进行第三次更精细的调整。
Rather than writing a specific routine or plug-in that answers the exact question, I just rely on the basic ideas and write variations of the code to handle all kinds of layout issues, not just text, including fitting divs, spans, images,... by width, height, area,... within a container, matching another element.... 我没有编写特定的例程或插件来回答确切的问题,我只是依靠基本思想并编写代码的变体来处理各种布局问题,而不仅仅是文本,包括适合的div,span,images。 ..按宽度,高度,面积...在一个容器内,与另一个元素匹配。
Here's an example: 这是一个例子:
var nWindowH_px = jQuery(window).height();
var nWas = 0;
var nTry = 5;
do{
nWas = nTry;
nTry *= 2;
jQuery('#divTitle').css('font-size' ,nTry +'px');
}while( jQuery('#divTitle').height() < nWindowH_px );
nTry = nWas;
do{
nWas = nTry;
nTry = Math.floor( nTry * 1.1 );
jQuery('#divTitle').css('font-size' ,nTry +'px');
}while( nWas != nTry && jQuery('#divTitle').height() < nWindowH_px );
jQuery('#divTitle').css('font-size' ,nWas +'px');