我有一个HTML表格,它的单元格中有从0开始递增的数字(从左到右,从下到上)。
我在CSS中固定了单元格的width和height (在我的例子中,宽度是40px,高度是25px )。
当表变大时,其中的数字也会变大(例如,最后一个数字是1266356)。这会导致单元格比我在CSS中定义的更宽,从而相应地扩展整个表格。
相反,我希望数字的字体更小,以保持单元格的宽度为40px。
我如何使用CSS / Javascript / jQuery来实现这一点?
发布于 2010-04-22 21:39:35
可能有一个聪明的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");
}发布于 2010-04-23 00:42:49
您可以遍历表中的行和单元格,并检查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";
}
}
}发布于 2010-04-23 00:51:43
下面是我在dropdownReplacement plugin中做的事情
使用detectCharWidth函数,我计算出div中文本的平均字符宽度,然后我可以将其乘以文本的长度,看看它是否适合输入。
此时,您可以将字体更改为更小
下面是函数:
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];
}这应该会给你带来一些好处。
https://stackoverflow.com/questions/2691246
复制相似问题