簡體   English   中英

自動字體大小取決於DIV寬度

[英]Auto font-size depending on DIV width

我正在嘗試用一些HTML代碼替換JPG圖像。 按鈕的空白輪廓仍將用於標准按鈕以及懸停,但是我希望按鈕內的文本通過代碼進行處理。

但是問題在於某些按鈕中的多個單詞帶有多行,而其他按鈕只是幾個單詞。

我想讓按鈕的字體大小是動態的而不是設置,然后自動換行並相應地進行調整。

我發現這是我想要的: 字體大小取決於div的寬度和高度

但是我需要對文本進行自動換行。

這是我的示例,我似乎無法正常工作。 https://jsfiddle.net/5L39xq1n/

<div style="text-align:center;padding:20px 0;">DIV Button Test</div>

<div id="buttoncontainer">
    <div id="leftsidebuttons" class="leftsidebuttons">
        Multiple lines because of the number of words
    </div>
    <div id="leftsidebuttons" class="leftsidebuttons">
        Single Line
    </div>
    <div id="leftsidebuttons" class="leftsidebuttons">
        This is another multiple line button
    </div>
</div>

#buttoncontainer { width:175px; height:46px; line-height:46px; }

#leftsidebuttons { white-space:nowrap; }

.leftsidebuttons { color:#d5a200 !important; 
  background-color:blue;
  font-family: Arial, Helvetica, sans-serif;
    font-style:italic; 
  font-weight:700; 
  margin:5px 0;
  text-align:center; 
    word-wrap: break-word; 
}

.leftsidebuttons:hover { color:#ffcc00 !important; 
    background-color:red;
    text-align:center; 
}

var container = $("#buttoncontainer"),
text_container = $("#leftsidebuttons"),
start_size = 16,
container_width = container.width();

text_container.css('font-size', start_size + 'px');

while (text_container.width() > container_width) {
    text_container.css('font-size', start_size--+'px');
}

刪除white-space:nowrap應該可以完成這項工作。

您可以使用#leftsidebuttons {white-space:nowrap; },然后是{.wrap:break-word;}類的.leftsidebuttons !!

您需要解決許多問題:

  • 具有相同ID的多個元素
  • 不要使用div作為按鈕
  • 這種方法非常慢,基本上會嘗試每種字體大小直到適合為止。

如果您使用autodiv更改為button ,它將起作用。

https://jsfiddle.net/357d2ka6/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM