字体大小自动调整以适应

时间:2010-12-10 12:46:35

标签: javascript html css fonts font-size

我正在努力做标题所说的。我已经看到font-size可以是一个百分比。所以我的猜测是font-size: 100%;会这样做,但不会。

以下是一个示例:http://jsfiddle.net/xVB3t/

我可以得到一些帮助吗?

(如果必须以编程方式使用js进行,则没有问题)

7 个答案:

答案 0 :(得分:14)

这个问题可能对你有所帮助,但我警告你,虽然这可以通过jQuery解决它:

Auto-size dynamic text to fill fixed size container

祝你好运。

该问题的OP制作了一个插件,here is the link to it(& download

BTW我建议使用jQuery,因为Gaby pointed out这只能通过CSS来完成,你说你愿意使用js ...

答案 1 :(得分:5)

无法使用CSS。

100%与父元素的计算font-size有关。

参考:http://www.w3.org/TR/CSS2/fonts.html#font-size-props

对于jQuery解决方案,请查看Auto-size dynamic text to fill fixed size container

答案 2 :(得分:3)

我正在研究这项工作,我喜欢tnt-rox的答案,但我无法帮助,但我注意到它有一些可以削减的额外开销。

document.body.setScaledFont = function(){
    this.style.fontSize = (this.offsetWidth*0.35)+'%';
    return this;
}
document.body.setScaledFont();

如果将其添加到onresize事件中,那么削减开销会使其运行得更快一些。

如果您只想让特定元素集中的字体调整大小以适应,您还可以执行以下操作

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();
};

我刚注意到尼古拉斯'回答也有一些额外的开销。我把它清理了一下。从性能的角度来看,我并不是真正喜欢使用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");

以下是我使用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();
});

答案 3 :(得分:1)

有点晚了但这就是我解决这个问题的方法:

document.body.setScaledFont = function() {
    var f = 0.35, s = this.offsetWidth, fs = s * f;
    this.style.fontSize = fs + '%';
    return this
}
document.body.setScaledFont();

现在已设置基本文档字体。

对于dom中的其他元素,将字体大小设置为%或em,它们将按比例缩放。

答案 4 :(得分:0)

这里我有一个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();

答案 5 :(得分:0)

这是另一个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");

答案 6 :(得分:0)

这是一种查找所用文本高度的方法。 它很简单,仅使用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;
}