簡體   English   中英

jQuery CSS font-size

[英]jQuery CSS font-size

如果內容進入第二行,如何自動調整<td>的字體大小? 我知道如何使用CSS和jquery增加/減少字體大小但是如果具有特定類名文本的特定或所有td的長度超過一行,如何自動使字體大小變小。

<div style="overflow: hidden;" id="parentDiv" class="scroll">

 <div id="4" >
  <table id="t4" class="Table">
    <tbody>
      <tr>
        <td id="b4" class="bY"><table id="inner1" width="100%" cellpadding="3">
            <tbody>
              <tr>
                <td class="code" id="code4" width="172"></td>
                <td class="Num" id="Num4" width="50"></td>
                <td colspan="2" class="Name" id="Name"></td>
              </tr>
              <tr>
                <td class="code" width="172">&nbsp;</td>
                <td>&nbsp;</td>
                <td class="serial" width="110"></td>
                <td class="serial" width="322"></td>
              </tr>
            </tbody>
          </table></td>
      </tr>
    </tbody>
  </table>
</div>

你想要.filter() 對於大多數元素,這應該工作:

$(".myClass").filter(function()
{
    var el = $(this);
    el.css("white-space", "nowrap");
    var lineHeight = el.height();
    el.css("white-space", "");
    return el.height() > lineHeight;
}).css("font-size", "10pt");

處理表時,一行中的所有單元格都具有相同的高度,因此請檢查子元素的值。 例如,將所有內容包裝在div中。 但是,如果您必須直接對<td>采取行動:

$(function()
{
    $(".myClass td").filter(function()
    {
        var el = $(this);
        el.closest("tr").andSelf().css("white-space", "nowrap");
        var lineHeight = el.height();
        el.css("white-space", "normal");
        var textWraps = el.height() > lineHeight;
        el.closest("tr").andSelf().css("white-space", "");
        return textWraps;
    }).css("font-size", "10pt");
});

沒有一種直接的方法來獲得文本內容的寬度(以像素為單位)。 但是,您可以通過將字符數乘以每個字符的平均像素寬度來獲得合理的估計值 - 這將根據字體而變化,並且最適合像Courier這樣的固定寬度字體。 這也假設所有內容都是簡單文本而沒有額外的格式。

大多數字體的字符寬度小於高度,因此假設width = height肯定會起作用。

例:

var fontSize = parseInt($('.my-td-class').css('font-size')); // get default font size

function updateFont() {
  var e = $('#some-element');
  while (e.text().length * fontSize > e.width()) {
    fontSize *= 0.8;  // reduce to 80%
    e.css('font-size', fontSize + 'px');
  }
}

編輯:根據其他答案,您也可以將此技術應用於高度。 只需確保寬度/高度比較反映當前字體大小而不是任何硬編碼值。

var newFontSize = 8
if $('td').filter(function() {
    return $(this).height() >  20 
}).css("font-size", newFontSize);

玩高度> 20和newFontsize來獲得你想要的。

暫無
暫無

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

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