[英]auto adjustment of font size to fit in a fixed shaped div
這是我正在使用的小提琴:
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");
});
順便提一下,會有更好的解決方案。 這只是演示了使用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.