Javascript 字体大小自动调整以适应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4408937/
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
Font size auto adjust to fit
提问by Diego
I'm trying to do what the title says. I've seen that font-size
can be a percentage. So my guess was that font-size: 100%;
would do it, but no.
我正在努力按照标题所说的去做。我已经看到这font-size
可以是一个百分比。所以我的猜测是font-size: 100%;
可以做到,但没有。
Here is an example: http://jsfiddle.net/xVB3t/
这是一个例子:http: //jsfiddle.net/xVB3t/
Can I get some help please?
我可以得到一些帮助吗?
(If is necesary to do it programatically with js there is no problem)
(如果需要用 js 以编程方式进行,则没有问题)
采纳答案by Trufa
This question might help you out but I warn you though this solves it through jQuery:
这个问题可能会帮助你,但我警告你,虽然这可以通过 jQuery 解决它:
Auto-size dynamic text to fill fixed size container
Good luck.
祝你好运。
The OP of that question made a plugin, here is the link to it(& download)
BTW I'm suggesting jQuery because as Gaby pointed outthis can't be done though CSS only and you said you were willing to use js...
顺便说一句,我建议使用 jQuery,因为正如Gaby 所指出的,这不能仅通过 CSS 来完成,并且您说您愿意使用 js ...
回答by Gabriele Petrioli
Can't be done with CSS.
不能用 CSS 来完成。
100% is in relation to the computed font-size
of the parent element.
100%font-size
与父元素的计算有关。
reference: http://www.w3.org/TR/CSS2/fonts.html#font-size-props
参考:http: //www.w3.org/TR/CSS2/fonts.html#font-size-props
For a jQuery solution look at Auto-size dynamic text to fill fixed size container
对于 jQuery 解决方案,请查看Auto-size dynamic text to fill fixed size container
回答by Eeems
I was looking into this for work and I liked tnt-rox's answer, but I couldn't help but notice that it had some extra overhead that could be cut out.
我正在研究这个工作,我喜欢 tnt-rox 的回答,但我不禁注意到它有一些额外的开销可以削减。
document.body.setScaledFont = function(){
this.style.fontSize = (this.offsetWidth*0.35)+'%';
return this;
}
document.body.setScaledFont();
Cutting out the overhead makes it run a little bit quicker if you add it to an onresize event.
如果您将其添加到 onresize 事件,则减少开销会使其运行得更快一些。
If you are only looking to have the font inside a specific element set to resize to fit, you could also do something like the following
如果您只想将特定元素内的字体设置为调整大小以适合,您还可以执行以下操作
window.onload = function(){
var scaledFont = function(el){
if(el.style !== undefined){
el.style.fontSize = (el.offsetWidth*0.35)+'%';
}
return el;
}
navs = document.querySelectorAll('.container>nav'),
i;
window.onresize = function(){
for(i in navs){
scaledFont(navs[i]);
}
};
window.onresize();
};
I just noticed nicolaas' answer also had some extra overhead. I've cleaned it up a bit. From a performance perspective, I'm not really a fan of using a while loop and slowly moving down the size until you find one that fits.
我只是注意到尼古拉斯的回答也有一些额外的开销。我已经清理了一点。从性能的角度来看,我并不是很喜欢使用 while 循环并慢慢减小尺寸直到找到合适的。
function setPageHeaderFontSize(selector) {
var $ = jQuery;
$(selector).each(function(i, el) {
var text = $(el).text();
if(text.length) {
var span = $("<span>").css({
visibility: 'hidden',
width: '100%',
position: 'absolute',
'line-height': '300px',
top: 0,
left: 0,
overflow: 'visible',
display: 'table-cell'
}).text(text),
height = 301,
fontSize = 200;
$(el).append(span);
while(height > 300 && fontSize > 10) {
height = span.css("font-size", fontSize).height();
fontSize--;
}
span.remove();
$(el).css("font-size", fontSize+"px");
}
});
}
setPageHeaderFontSize("#MyDiv");
And here is an example of my earlier code using jquery.
这是我使用 jquery 的早期代码的示例。
$(function(){
var scaledFont = function(el){
if(el.style !== undefined){
el.style.fontSize = (el.offsetWidth*0.35)+'%';
}
return el;
};
$(window).resize(function(){
$('.container>nav').each(scaledFont);
}).resize();
});
回答by tnt-rox
A bit late but this is how I approach this problem:
有点晚了,但这就是我解决这个问题的方式:
document.body.setScaledFont = function() {
var f = 0.35, s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
}
document.body.setScaledFont();
The base document font is now set.
现在已设置基本文档字体。
For the rest of your elements in the dom set font sizes as % or em and they will scale proportionately.
对于 dom 中的其余元素,将字体大小设置为 % 或 em,它们将按比例缩放。
回答by nicolaas thiemen francken
Here is another jQuery solution ...
这是另一个jQuery解决方案......
/**
* Resizes page header font-size for the text to fit.
* basically we add a hidden span into the header,
* put the text into it and then keep reducing the super large font-size
* for as long as the height of the span exceeds the super
* tall line-height set for the test (indicating there is more than one line needed
* to show the text).
*/
function setPageHeaderFontSize(selectorString) {
jQuery(selectorString).each(
function(i, el) {
var text = jQuery(el).text();
var length = text.length;
if(length) {
var id = "TestToSeeLengthOfElement_" + i;
jQuery(el).append("<span style='visibility: hidden; width: 100%; position: absolute; line-height: 300px; top: 0; left: 0; overflow: visible; display: table-cell;' id='"+id+"'>"+text+"</span>");
var innerEl = jQuery("#"+id);
var height = 301;
var fontSize = 200;
while(height > 300 && fontSize > 10) {
height = jQuery(innerEl).css("font-size", fontSize).height();
fontSize--;
}
jQuery(innerEl).remove();
jQuery(el).css("font-size", fontSize+"px");
}
}
);
}
//you can run it like this... using any jQuery enabled selector string (e.g. h1.pageHeaders works fine).
setPageHeaderFontSize("#MyDiv");
回答by Launch9
Here's a way to find the height of the text that you are using. It's simple and only uses javascript. You can use this to adjust your text relative to the height you want.
这是一种查找您正在使用的文本高度的方法。它很简单,只使用 javascript。您可以使用它来相对于所需的高度调整文本。
function getTextHeight(text, fontSize) {
var numberOfLines = 0;
var STL = text;
for(var i = 0; i < STL.length; i++){
if(STL[i] === '<'){
try{
if(STL[i + 1] === 'b' && STL[i + 2] === 'r' && STL[i + 3] === '>'){
numberOfLines++;
}
}
catch(err){
break;
}
}
return (numberOfLines + 1) * fontSize;
}
回答by Karl Adler
here I have a mootools solution:
在这里,我有一个 mootools 解决方案:
Element.implement("fitText", function() {
var e = this.getParent();
var maxWidth = e.getSize().x;
var maxHeight = e.getSize().y;
console.log(maxWidth);
var sizeX = this.getSize().x;
var sizeY = this.getSize().y;
if (sizeY <= maxHeight && sizeX <= maxWidth)
return;
var fontSize = this.getStyle("font-size").toInt();
while( (sizeX > maxWidth || sizeY > maxHeight) && fontSize > 4 ) {
fontSize -= .5;
this.setStyle("font-size", fontSize + "px");
sizeX = this.getSize().x;
sizeY = this.getSize().y;
}
return this;
});
$$("span").fitText();