![](/img/trans.png)
[英]Jquery fixed header and a fixed column for a table, width of cell may be varying
[英]How to set the width of each header cell in a table (with fixed header) to be the same to the biggest in its column, and make the browser respect it?
這是臭名昭着的表:
在一年中的這個時候,我的老板想要我修復表格的標題,這樣用戶就可以向下滾動表格並繼續閱讀標題。 我想保留表的原始預先計算的維度,我的意思是,每個列在創建時的寬度(寬度不是由CSS建立)然后調整標題使其列與列的列相匹配身體。 根據我在Stackoverflow中找到的一些答案,我開始制作標題和表格的主體display: block
。 之后,我寫了這個:
function setTableHeadDimensions() {
var $taskTable = $('.tablaTareas_PEMVISUALIZA'),
$firstRow = $taskTable.find('tbody > tr:first-child'),
$firstRowTds = $firstRow.find('td'),
$firstRowHead = $taskTable.find('thead > tr:first-child'),
$secondRowHead = $taskTable.find('thead > tr:eq(1)'),
$firstRowHeadThs = $firstRowHead.find('th'),
$secondRowHeadThs = $secondRowHead.find('th'),
i = 0,
cells = [];
//We prepare CSS, so we can specify width.
$taskTable
.css('table-layout', 'fixed')
.find('td, th').each(function () {
var $tdh = $(this);
$tdh.css('box-sizing', 'border-box');
$tdh.css('overflow', 'hidden');
});
//Cells of the first row of the table head.
for (i = 0; i < 3; i++) {
cells.push($($firstRowHeadThs[i]));
}
//Cells of the second row of the table head.
for (i = 0; i < $secondRowHeadThs.length; i++) {
cells.push($($secondRowHeadThs[i]));
}
//Rest of the cells for the first row.
for (i = 5; i < $firstRowHeadThs.length; i++) {
cells.push($($firstRowHeadThs[i]));
}
//Try to set the width of the current column's header cell
//to the biggest cell width in the column.
for (i = 0; i < cells.length; i++) {
var maxWidth = 0;
$taskTable.find('td:nth-child(' + (i + 1) + ')').each(function () {
var $el = $(this);
maxWidth = Math.max(maxWidth, $el.width());
});
cells[i].width(maxWidth);
}
}
但是,正如您在圖片中看到的那樣,瀏覽器不想合作。 更重要的是,它建立了單元格的寬度,但是與一個與其對應列的寬度不匹配的數字:
更重要的是,它與它應該匹配的行的寬度不匹配:
所以我有兩個問題:
這是一個代碼庫,示例縮減到最低限度: Codepen示例
我解決了 實際上,有兩個問題:
第一個是jQuery.width()
只返回單元格內容的寬度,沒有填充和邊距(即使你指定border-sizing: border-box
)。 我發現更自然地使用jQuery.css('width')
然后在我的計算中考慮邊框和填充,而沒有指定border-sizing: border-box
因為使用border-sizing: border-box
檢索寬度然后設置它在另一個元素與匹配兩個寬度的想法可能是容易出錯(我有問題)。
第二個是如果在表的標題中使用rowspan
。 在這種情況下,您必須確定正在進行正確計算的行的寬度,而不僅僅是其中一行跳過其余行將適應的行。
這是解決方案的代碼: http ://codepen.io/PolarKuma/pen/BQXMbO
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.