这是臭名昭著的表:
老板希望我在每年的这个时候固定表格的标题,以便用户可以向下滚动表格并继续阅读标题。我想保留表格的原始预先计算的尺寸,我的意思是,每列在创建时具有的宽度(宽度不是由CSS确定的),然后调整标题,以便其列与表的列匹配 body 。遵循在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 example
最佳答案
我解决了实际上,存在两个问题:
第一个是jQuery.width()
仅返回单元格内容的宽度,没有填充和边距(即使您指定border-sizing: border-box
)。我发现更自然地使用jQuery.css('width')
,然后在计算时考虑边框和填充,而无需指定border-sizing: border-box
,因为使用border-sizing: border-box
检索宽度,然后将其设置为另一个元素的想法是将两个宽度都匹配可能容易出错(我遇到了问题用它)。
第二个是如果在表头中使用rowspan
。在这种情况下,您必须确定要进行正确计算的行的宽度,而不仅仅是其中之一希望其他行能够适应。
这是解决方案的codepen:http://codepen.io/PolarKuma/pen/BQXMbO