【问题标题】:Font size auto adjust to fit字体大小自动调整以适应
【发布时间】:2011-05-23 11:26:27
【问题描述】:

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

这里是一个例子:http://jsfiddle.net/xVB3t/

我能得到一些帮助吗?

(如果有必要用js以编程方式做到这一点没有问题)

【问题讨论】:

  • 谢谢。任何想看的人都可以在这里看到它:jsfiddle.net/xVB3t/2
  • 非常感谢您分享已解决的问题,这真的很有帮助,应该如何做+1!
  • @ChrisBaker 链接的问题是询问 jQuery,这个问题不是,所以我不会将其标记为重复。
  • @PeterOlson 考虑到接受的答案的全部内容都链接到该答案,如果没有链接,这个接受的答案将 100% 无用,这是一个应该标记为的问题的完美示例重复。否则,这是“你的答案在另一个城堡”的一个很好的例子,这是一个当你看到它时要避免和消除的问题。

标签: javascript html css fonts font-size


【解决方案1】:

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

Auto-size dynamic text to fill fixed size container

祝你好运。

那个问题的OP做了一个插件,here is the link to it(&download)

顺便说一句,我建议使用 jQuery,因为 Gaby pointed out 仅通过 CSS 无法做到这一点,并且您说您愿意使用 js...

【讨论】:

【解决方案2】:

不能用 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

【讨论】:

  • 谢谢@Gaby,现在我明白了font-size 的百分比:)。但仍在寻找答案。
  • @Diego,更新了答案,其中包含指向 SO 中另一个答案的链接。 @Akinator 也发布了它。
  • 如此简单,我迷失在 JavaScript 解决方案中。普通的 CSS 解决了这个问题。谢谢。
【解决方案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();
};

我刚刚注意到 nicolaas 的回答也有一些额外的开销。我已经清理了一下。从性能的角度来看,我不太喜欢使用 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();
});

【讨论】:

    【解决方案4】:

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

    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,它们将按比例缩放。

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

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

          【讨论】:

            猜你喜欢
            • 2012-08-10
            • 2016-04-21
            • 1970-01-01
            • 2013-06-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-26
            相关资源
            最近更新 更多