![](/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.