繁体   English   中英

自动调整字体大小以适合固定形状的div

[英]auto adjustment of font size to fit in a fixed shaped div

这是我正在使用的小提琴:

http://jsfiddle.net/LbUFg/

html代码是:

<div class="body"> 
  <div class="variation1 font700 green1"> 
    <h2> 
      sample <span class="divider"> arrowshape </span>
    </h2>
  </div>
  <div class="clear"></div>
  <div class="variation2 font700 green2">
    <h2>
      as the  text increases the font size must decrease but the block height must remain same <span class="divider"> as the  text increases the font size must decrease but the block height must remain same </span>
    </h2> 
  </div>
  <div class="clear"></div>

  <!-- OTHER HTML -->

</div>

我想调整文本,使其适合div而不改变所示箭头块的尺寸(大小)(文本大小可以改变而不是块大小)。 箭头块必须看起来像示例箭头和Im面临问题,如变体2中所示。 有人可以帮我解决这个问题吗?

试试一个jquery插件FITTEXT这会对你有所帮助

你必须使用javascript。 CSS本身无法处理这个问题。

对于一个糟糕的例子:

$(".font700").each(function(i, obj) {
    newSize = $(obj).text().length;
    newSize = 64 - newSize;
    newSize = (newSize < 10) ? 10 : newSize;
    $(obj).css("font-size", newSize + "px");
});

的jsfiddle

顺便提一下,会有更好的解决方案。 这只是演示了使用javascript(特别是jQuery)的可能性。 您可以找到一些插件,如FitText ,可以为您解决很多这些问题。

(感谢Grim的链接)

对于那些不喜欢像FitText这样的插件的人,我只是通过查看当前的平均字母宽度来计算字体大小以适合包含元素(复杂化:多行,通过暂时改变css宽度来解决这里的问题) )HTML是

<div><h1><a><span>Title</span></a></h1></div>

和jQuery:

$("h1").each(function() {
    var l = $(this).text().length;
    var w = $(this).prop("offsetWidth");  //clientWidth doesn't always work
    var old_pos = $(this).find("a").css("position");
    var old_w = $(this).find("a").css("width");
    $(this).find("a").css("position", "absolute");
    $(this).find("a").css("width", "1000px");
    var w2 = $(this).find("span").prop("offsetWidth");
    var h2 = $(this).find("span").prop("offsetHeight");
    var c = 1.2*(w2/h2)/l;  // Current proportion of font width, 1.2 is constant
    var fontsize = w/l/c;
    fontsize = (fontsize<10)?10:fontsize;       //limit min
    //$(this).append(" "+c+"/"+fontsize);  //test
    //Set font size to fill width of parent element
    $(this).css("font-size",fontsize+"px");
    $(this).find("a").css("position", old_pos);
    $(this).find("a").css("width", old_w);
});

这会在砌体样式的网格中调整我的字体大小

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM