如果您不使用 IE 或 FireFox,请尝试直接点击下面的“运行代码片段” - 我认为它会向您展示您需要“知道”的所有内容所有的唠叨。它是完全没有任何 JavaScript 的粘性表头。只是 CSS / HTML。
我见过 许多复杂的解决方案,用于基于 JavaScript、JQuery 和 的 粘性 HTML 表格列 >高级 CSS。它们可能非常好,并且在多个浏览器中运行良好,但是下面的方法应该很容易实现(它不能再简单了)并且在除 IE11 和 FireFox 之外的所有最新浏览器中都原生支持。无需处理复杂性。
我还经常看到按顺序使用两个表的建议,其中第一个表固定仅显示列值,第二个表隐藏其列标题并仅显示值行。这看起来很笨重。
我也见过其他几种方法。
根据我的有限测试,以下适用于最新版本的 Edge、Chrome、Opera 和 Vivaldi,但在 IE 或 FireFox 中不是(不会出现错误,只是没有粘性标题 - 它会优雅地降级)。我没有设置足够的测试资源来准确验证兼容性。重要的是,没有一行 JavaScript 代码可以中断。
这个“解决方案”的核心是这个CSS提取:
th {
position: sticky;
top: 0px;
}
这似乎会使表格标题单元格<th> 粘在其父 div 的顶部边框 (top: 0px) 上,这显然是在最新浏览器版本中实现粘性列标题所需的全部内容。
此外,您可以在流中放置多个 div,每个 div 都有自己的表格,或者您可以将多个表格放在同一个 div 中。它似乎可以自动运行。
我有一个启用排序的大型测试表,当您单击粘性标题时,排序也可以正常工作。
以下示例已被缩减到最低限度,同时仍在尝试对整体方法进行适当的测试。我将发布第二个答案,其中包含一个较长的表格,其中包含适当的 thead 和 tbody 部分(不包括在这个简单的示例中)。
#testdiv {
background-color: wheat;
height: 180px;
width: 600px; /* Try commenting this out as well */
overflow: scroll;
}
th {
/* The two core settings for sticky table headers */
position: sticky;
top: 0px;
/* A few more settings for better display*/
background-color: purple;
color: white;
white-space: nowrap;
border: 1px solid black;
text-align: left;
}
table, td {
border-collapse: collapse;
border: 1px solid black;
white-space: nowrap; /* Try commenting this out as well */
}
<div id="testdiv">
<p>Just a leading paragraph for demonstration.</p>
<p>Scroll down and sideways to check the sticky table headers.</p>
<table id='testtable'>
<tr>
<th>This is the first column:</th>
<th>Column Two:</th>
<th>Third in line here:</th>
</tr>
<tr>
<td>A summer night a long time ago I saw a fox chase a firefly.</td>
<td>A winter night a long long time ago, I watched the aurora borealis dance in the sky.</td>
<td>Hello world.</td>
</tr>
<tr>
<td>What is your favorite color?</td>
<td>Time's Arrow.</td>
<td>Just a short while ago I was young.</td>
</tr>
<tr>
<td colspan="3">This is a colspan.</td>
</tr>
<tr>
<td>Live long and prosper.</td>
<td>Kosmonaut.</td>
<td>What is the airspeed velocity of an unladen swallow?</td>
</tr>
<tr>
<td>A base in space, just to protect the human race.</td>
<td>Unimatrix Zero.</td>
<td>Are there any women here?</td>
</tr>
<tr>
<td>Raven.</td>
<td>Beware, here be dragons.</td>
<td>Timeless.</td>
</tr>
<tr>
<td>Astronaut.</td>
<td>42</td>
<td>HTML and CSS, the fiddliest of endeavours.</td>
</tr>
<tr>
<td rowspan="3">This is rowspan.</td>
<td>Oh my God.</td>
<td>777</td>
</tr>
<tr>
<td>Holy Crap.</td>
<td>778</td>
</tr>
<tr>
<td>The neighbour of the beast.</td>
<td>668</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td colspan="2" rowspan="2">This is colspan and rowspan.</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>Three</td>
<td>Columns</td>
<td>Here</td>
</tr>
</table>
<p>A trailing paragraph for demonstration.</p>
<p>A trailing paragraph for demonstration.</p>
<p>A trailing paragraph for demonstration.</p>
<p>A trailing paragraph for demonstration.</p>
<p>A trailing paragraph for demonstration.</p>
</div>