[英]Getting the width of the contents of a td on a fixed table
我有一個數據表,之前我已經設置了使用jquery的寬度和table-layout: fixed
CSS中的table-layout: fixed
屬性。 稍后在我的代碼中,單元格的內容可能會更改,可能需要更改寬度。 結果就是這樣的小提琴。
如您所見,對於長字符串,單元格內容從其包含的單元格流出,並流入下一個單元格。 我想做的是在更新單元格后檢查其內容,以查看內容的寬度是否大於該單元格。 在我的小提琴中,有一條注釋行可以進行寬度更新:
$('.firstItem').width(202) //successfully fits my entry
問題是202
是硬編碼的,我似乎無法弄清楚如何獲得它。 我在td
上嘗試了.width()
.outerWidth()
和.innerWidth()
,試圖找到內容的寬度,但無濟於事。 我知道,如果我的內容是span
或類似的內容,則可以在其上調用我的width方法,但是我的大多數內容只是文本,我寧願不添加更多DOM元素,因為我的表已經在足夠大,可以減慢速度。
有沒有一種好的方法來獲取table
td
的文本內容的寬度?
只需在表格上設置寬度自動:
width: auto;
或使用textWidth代碼段:
$.fn.textWidth = function(text){
var org = $(this)
var html = $('<span style="postion:absolute;width:auto;left:-9999px">' + (text || org.html()) + '</span>');
$('body').append(html);
var width = html.width();
html.remove();
return width;
}
$('.firstItem').width($('td.firstItem').textWidth());
您應該給行指定一個id
,然后使用其scrollWidth
屬性值並更新此css規則,以將您的scrollWidth作為width:
th, td
th, td{
border: 1px solid black;
width: 203px; /* your scrollWidth value here */
height: 20px;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.