JavaScript 缩放文本以适应固定 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4165836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Scale Text to Fit in Fixed Div
提问by Stephen Watkins
In JavaScript/jQuery, how can I scale a varying-length line of text inside a fixed-width Div so that the one line always fits inside the Div (as one line)?
在 JavaScript/jQuery 中,如何在固定宽度的 Div 内缩放不同长度的文本行,以便一行始终适合 Div(作为一行)?
Thanks.
谢谢。
回答by sworoc
This is somewhat of a hack, but will do what you want.
这有点像黑客,但会做你想做的。
<div id="hidden-resizer" style="visibility: hidden"></div>
Place this at the bottom of your page, where it will not be moving other elements on the page.
将它放在页面底部,它不会移动页面上的其他元素。
Then do this:
然后这样做:
var size;
var desired_width = 50;
var resizer = $("#hidden-resizer");
resizer.html("This is the text I want to resize.");
while(resizer.width() > desired_width) {
size = parseInt(resizer.css("font-size"), 10);
resizer.css("font-size", size - 1);
}
$("#target-location").css("font-size", size).html(resizer.html());
回答by ?ime Vidas
HTML:
HTML:
<div class="box" style="width:700px">This is a sentence</div>
<div class="box" style="width:600px">This is a sentence</div>
<div class="box" style="width:500px">This is a sentence</div>
<div class="box" style="width:400px">This is a sentence</div>
JavaScript:
JavaScript:
$( '.box' ).each(function ( i, box ) {
var width = $( box ).width(),
html = '<span style="white-space:nowrap"></span>',
line = $( box ).wrapInner( html ).children()[ 0 ],
n = 100;
$( box ).css( 'font-size', n );
while ( $( line ).width() > width ) {
$( box ).css( 'font-size', --n );
}
$( box ).text( $( line ).text() );
});
Live demo:http://jsfiddle.net/e8B9j/2/show/
现场演示:http : //jsfiddle.net/e8B9j/2/show/
Remove "/show/" from the URL to view the code.
从 URL 中删除“/show/”以查看代码。
回答by Michi Kono
I have written a jQuery plugin to do this:
我写了一个 jQuery 插件来做到这一点:
http://michikono.github.com/boxfit
http://michikono.github.com/boxfit
The plugin will scale the text both horizontally and vertically to the maximum available size inside the box and then center it.
该插件会将文本水平和垂直缩放到框内的最大可用大小,然后将其居中。
The only thing you need to do is define a div with text inside it:
您唯一需要做的就是定义一个包含文本的 div:
<div id="scale">some text</div>
And then call:
然后调用:
$('#scale').boxfit()
The method will accept some arguments to disable/enable text wrapping and centered alignment.
该方法将接受一些参数来禁用/启用文本换行和居中对齐。
回答by Benjamin
For new Browsers you can use Inline-SVG. This can be scaled like an image via CSS .. !
对于新的浏览器,您可以使用 Inline-SVG。这可以通过 CSS 像图像一样缩放 ..!
.smallerVersion{
max-width: 50%
}
<!DOCTYPE html>
<html>
<head>
<title>Scale SVG example</title>
</head>
<body>
<h2>Default version:</h2>
<svg viewBox="0 0 240 80" xmlns="http://www.w3.org/2000/svg">
<style>
.small { font: italic 13px sans-serif; }
.heavy { font: bold 30px sans-serif; }
/* Note that the color of the text is set with the *
* fill property, the color property is for HTML only */
.Rrrrr { font: italic 40px serif; fill: red; }
</style>
<text x="20" y="35" class="small">My</text>
<text x="40" y="35" class="heavy">cat</text>
<text x="55" y="55" class="small">is</text>
<text x="65" y="55" class="Rrrrr">Grumpy!</text>
</svg>
<h2>Scaled version:</h2>
<svg class="smallerVersion" viewBox="0 0 240 80" xmlns="http://www.w3.org/2000/svg">
<style>
.small { font: italic 13px sans-serif; }
.heavy { font: bold 30px sans-serif; }
/* Note that the color of the text is set with the *
* fill property, the color property is for HTML only */
.Rrrrr { font: italic 40px serif; fill: red; }
</style>
<text x="20" y="35" class="small">My</text>
<text x="40" y="35" class="heavy">cat</text>
<text x="55" y="55" class="small">is</text>
<text x="65" y="55" class="Rrrrr">Grumpy!</text>
</svg>
</body>
</html>
(width: 100%;
)
( width: 100%;
)
回答by Hoffmann
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. 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:
大多数其他答案使用循环来减小字体大小,直到它适合 div,这非常慢,因为每次字体更改大小时页面都需要重新渲染元素。我最终不得不编写自己的算法,使其以一种允许我定期更新其内容的方式执行,而不会冻结用户浏览器。我添加了一些其他功能(旋转文本、添加填充)并将其打包为 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 必须有固定的高度和宽度,它不支持将文本换行成多行。
Edit2: I have now fixed those problems and limitations and added more options. You can set maximum font-size and you can also choose to limit the font-size using either width, height or both (default is both). I will work into accepting a max-width and max-height values in the wrapper element.
Edit2:我现在已经解决了这些问题和限制,并添加了更多选项。您可以设置最大字体大小,也可以选择使用宽度、高度或两者(默认为两者)来限制字体大小。我将努力接受包装元素中的 max-width 和 max-height 值。
回答by casablanca
I don't know of an exact way, but here's an approximation:
我不知道确切的方法,但这是一个近似值:
var factor = 1/3; // approximate width-to-height ratio
var div = $('#mydiv');
div.css('font-size', div.width() / (div.text().length * factor) + 'px');
You will need to adjust factor
based on the font you are using. 1/3 seems to work okay for Times New Roman.
您将需要factor
根据您使用的字体进行调整。1/3 似乎适用于 Times New Roman。
回答by EmKay
Inside your div, have the text in a span that has no padding. Then the span's width will be the length of the text.
Untested code for finding the correct font-size to use:
在您的 div 中,将文本放在没有填充的跨度中。那么跨度的宽度将是文本的长度。
用于查找要使用的正确字体大小的未经测试的代码:
var objSpan = $('.spanThatHoldsText');
var intDivWidth = $('.divThatHasAFixedWidth').width();
var intResultSize;
for (var intFontSize = 1; intFontSize < 100; intFontSize++)
objSpan.css('font-size', intFontSize);
if (objSpan.width() > intDivWidth) {
intResultSize = intFontSize - 1;
break;
}
}
objSpan.css('font-size', intResultSize);
回答by testere
回答by Arunoda Susiripala
Modified version of @sworoc with the support of the target class
在目标类的支持下修改了@sworoc 的版本
function resizeText(text, size, target) {
var fontSize = 0;
var resizer = $('<span>');
resizer.html(text).hide();
resizer.attr('class', target.attr('class'));
$('body').append(resizer);
while(resizer.width() < size) {
fontSize++
resizer.css("font-size", fontSize);
}
target.css('font-size', fontSize).html(text);
resizer.remove();
}
Usage
用法
resizeText("@arunoda", 350, $('#username'));
回答by bradgonesurfing
Here is a coffeescript solution I came up with. I clone the element that is needing to have it's font resized then remove that at the end of the calculation. To increase performance I have some code that only executes the calculation after resizing has stopped for 200ms.
这是我想出的一个咖啡脚本解决方案。我克隆需要调整其字体大小的元素,然后在计算结束时将其删除。为了提高性能,我有一些代码仅在调整大小停止 200 毫秒后才执行计算。
Tag elements with class autofontfor this to be done unobtrusively.
使用类autofont标记元素,以便不显眼地完成。
#
# Automagically resize fonts to fit the width of the
# container they are in as much as possible.
#
fixfonts = ->
scaler = 1.2
for element in $('.autofont')
size = 1
element = $(element)
desired_width = $(element).width()
resizer = $(element.clone())
resizer.css
'font-size': "#{size}em"
'max-width': desired_width
'display': 'inline'
'width': 'auto'
resizer.insertAfter(element)
while resizer.width() < desired_width
size = size * scaler
resizer.css
'font-size': "#{size}em"
$(element).css
'font-size': "#{size / scaler }em"
resizer.remove()
$(document).ready =>
fixfonts()
timeout = 0
doresize = ->
timeout--
if timeout == 0
fixfonts()
$(window).resize ->
timeout++
window.setTimeout doresize, 200