簡體   English   中英

如何根據單元格內容更改表格單元格中的字體大小?

[英]How to change the font size in table cells according to cells content?

我有一個HTML表格,其單元格中從0開始遞增數字(從左到右,從上到下)。

我在CSS中修復了單元格的widthheight (40px寬度,25px高度,在我的情況下)。

當表變大時,其中的數字也變大(例如,最后一個數字是1266356)。 這導致單元格比CSS中定義的要寬,這會相應地擴展整個表格。

相反,我希望數字的字體更小,以保持單元格的寬度40px。

如何使用CSS / Javascript / jQuery實現這一目標?

可能有一種聰明的CSS方法可以做到這一點,但在jQuery中,類似下面的東西可以做到這一點:

// if the length exceeds a predefined limit
if($('.someCell').text().length > 5) {

    // change the font size of it's text
    $('.someCell').css("font-size", "8px");
}

您可以循環遍歷表中的行和單元格,並檢查innerHTML的長度。 它可能看起來像這樣:

var tableRows = document.getElementById("myTable").rows;
maxLength = 5;

for(var i = 0; i<rows.length;i++)
{
    var rowCells = tableRows[i].cells.length;
    for(var a = 0; a<rows.length;a++)
    {
        if(rowCells[a].innerHTML.length > maxLength)
        {
            rowCells[a].style.fontSize = "8px";
        }
    }
}

這是我在dropdownReplacement插件中所做的事情:

使用detectCharWidth函數我找出div中文本的avg char寬度,然后我可以將它乘以文本的長度,看它是否適合輸入。

此時你可以將字體更改為更小

這是功能:

var detectedCharWidths = {};
var detectCharWidth = function(testText){
     var val = testText || "a b c d e f 1 2 3 4 5 6 A B C D E F ! ! %"; //correct detection depends on this more then anything
    if(!detectedCharWidths[val]){
    var $inp = $("<span>", {
     "text":val,
    // "class":opts.selectClass,
     "css": {"background":"none", "margin":0, "padding":0, "overflow":"visible", "width":"auto", "color":"#FFF"}
    });
    $body.append($inp);
    detectedCharWidths[val] = ($inp.width() / val.length);
    $inp.remove();
    }
    return detectedCharWidths[val];
  }

那會讓你有所幫助

我編寫了一個函數來幫助您根據容器調整字體。

function adjustFont(x) {
        if (x.height() <= 36)
            return x.css("font-size");
        else {
            var sizeInPx = x.css("font-size").split("px")[0];
            x.css("font-size", (sizeInPx - 1) + "px");
            adjustFont(x);
        }
    }

根據您的需要改變高度我將它修好了36。

你必須傳遞你的td元素:

adjustFont($(yourTdElementHere));

如果需要,可以循環遍歷表並傳遞每個元素。

暫無
暫無

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

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