gpt4 book ai didi

javascript - 如何将表格(固定标题)中每个标题单元格的宽度设置为与其列中最大的宽度相同,并使浏览器尊重它?

转载 作者:搜寻专家 更新时间:2023-10-31 08:51:45 25 4
gpt4 key购买 nike

这是臭名昭著的表格:

enter image description here

我的老板希望我在每年的这个时候固定表格的标题,以便用户可以向下滚动表格并继续阅读标题。我想保留表格的原始预计算尺寸,我的意思是,每列在创建时的宽度(宽度不是由 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);
}
}

但是,正如您在图片中看到的,浏览器不想合作。更重要的是,它确定了单元格的宽度,但数字与其对应列的宽度不匹配:

enter image description here

而且,它不匹配它应该匹配的行的宽度:

enter image description here

所以我有两个问题:

  1. 为什么浏览器会这样运行?
  2. 如何以与 IE8 兼容的方式解决此问题? (请不要花哨的 CSS3 解决方案)

这是一个 codepen,示例被简化为最低限度:Codepen example

最佳答案

我解决了。实际上,有两个问题:

第一个是jQuery.width()只返回单元格内容的宽度,没有padding和margin(即使你指定了border-sizing: border-box )。我发现使用 jQuery.css('width') 更自然,然后在我的计算中考虑边框和填充,而不指定 border-sizing: border-box 因为使用 border-sizing: border-box 检索宽度,然后将其设置在另一个元素中以匹配两个宽度的想法可能容易出错(我遇到了问题)。

第二个是如果您在表格的标题中使用 rowspan。在这种情况下,您必须确定所涉及的行的宽度并进行适当的计算,而不仅仅是其中一列跳到其余行将适应的宽度。

这是带有解决方案的代码笔:http://codepen.io/PolarKuma/pen/BQXMbO

关于javascript - 如何将表格(固定标题)中每个标题单元格的宽度设置为与其列中最大的宽度相同,并使浏览器尊重它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41365296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com