能否仅用 CSS 在点击表格单元格后高亮对应列表头?
数据阿明
可以。如果只需在单元格或其内部元素拥有焦点时保留高亮,可以用纯 CSS 实现:让单元格能够获得焦点,通过 :has() 找到表格,再用 :nth-child() 匹配对应列的表头。浏览器需要支持 :has()。
普通 td 默认不能通过这种方式获得焦点,通常需要给它添加 tabindex="0"。如果完全不能修改 HTML,且单元格内部也没有可聚焦元素,这个方案就不适用。
实现示例
下面是一个没有合并单元格的三列表格。点击数据单元格后,对应列表头会高亮;也可以使用 Tab 键移动焦点。
<style>
.orders {
border-collapse: collapse;
}
.orders th,
.orders td {
border: 1px solid #ccc;
padding: 8px 12px;
}
.orders:has(> tbody > tr > td:nth-child(1):focus-within)
> thead > tr > th:nth-child(1),
.orders:has(> tbody > tr > td:nth-child(2):focus-within)
> thead > tr > th:nth-child(2),
.orders:has(> tbody > tr > td:nth-child(3):focus-within)
> thead > tr > th:nth-child(3) {
background-color: #ffe08a;
color: #222;
}
.orders td:focus-visible {
outline: 2px solid #1565c0;
outline-offset: -2px;
}
</style>
<table class="orders">
<thead>
<tr>
<th scope="col">商品</th>
<th scope="col">数量</th>
<th scope="col">单价</th>
</tr>
</thead>
<tbody>
<tr>
<td tabindex="0">商品 A</td>
<td tabindex="0">2</td>
<td tabindex="0">100</td>
</tr>
<tr>
<td tabindex="0">商品 B</td>
<td tabindex="0">1</td>
<td tabindex="0">200</td>
</tr>
</tbody>
</table>
选择器如何工作
以第二列为例:
.orders:has(> tbody > tr > td:nth-child(2):focus-within)
> thead > tr > th:nth-child(2) {
background-color: #ffe08a;
}
td:nth-child(2):focus-within 匹配拥有焦点或包含焦点元素的第二个数据单元格。:has() 据此匹配整个表格,后面的选择器再选中第二个表头单元格。
:focus-within 也适用于单元格内的 input、button 等元素获得焦点的情况。如果交互始终发生在这些元素上,就可以省去相应 td 的 tabindex。
标准表格结构中,thead 与 th 之间还有 tr,因此这里使用 thead > tr > th。
使用时的限制
- 焦点移到表格之外后,高亮会消失。点击空白区域是否移走焦点,取决于浏览器行为。
:active也不能替代持久选中,因为它通常只在按下鼠标期间生效。 - 上面的 CSS 分别指定了第 1、2、3 列。增加列数时需要补充规则;这些选择器不会自动把数据单元格的列序号传给表头。
:nth-child()按同一行中元素的位置计数,不计算colspan、rowspan形成的视觉列,因此合并单元格需要另行处理。多层表头也需要明确映射关系。- 给大量单元格添加
tabindex="0"会增加 Tab 停靠点。如果单元格已有可操作控件,可以优先利用控件的焦点。
如果需要点击后一直保留选中列,直到再次选择其他列,可以考虑用 radio 和 :checked 保存状态,但需要调整 HTML 结构。对于动态列、复杂表头或完整的表格键盘交互,使用 JavaScript 管理选中状态通常更容易维护。
备注:内容仅供参考。
