Estaba buscando trabajo y me gustó la respuesta de tnt-rox, pero no pude evitar darme cuenta de que tenía algunos gastos adicionales que podrían eliminarse.
document.body.setScaledFont = function(){
this.style.fontSize = (this.offsetWidth*0.35)+'%';
return this;
}
document.body.setScaledFont();
Cortar la sobrecarga hace correr un poco más rápido si lo añade a un evento onresize.
Si sólo está buscando para tener la fuente dentro de un elemento específico establecido para cambiar el tamaño para adaptarse, también se puede hacer algo como lo siguiente acabo respuesta
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();
};
Nicolaas notado también tenía algo extra por encima. Lo he limpiado un poco. Desde una perspectiva de rendimiento, no soy realmente un fanático de usar un ciclo while y moverme lentamente hacia abajo hasta encontrar uno que encaje.
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");
Y aquí es un ejemplo de mi código anterior utilizando 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();
});
Gracias. Aquí está para cualquiera que quiera verlo: http://jsfiddle.net/xVB3t/2/ – Diego
muchas gracias por compartir el problema resuelto, que es realmente útil y es cómo deben hacerse las cosas +1! – Trufa
posible duplicado de [texto dinámico de tamaño automático para llenar el contenedor de tamaño fijo] (http://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container) –