首页 > 解决方案 > CSS:基于标题类将类应用于 tbody 单元格(在同一列中)

问题描述

找不到任何东西,所以这是我的标记:

<style>
table {
  width:300px;
  border-collapse:collapse;
}

th.price
{
  text-align:right;
  background:yellow;
}

th, td
{
  border:1px solid #aaa;
}
</style>

<table>
  <thead><tr><th>Item</th><th class="price">Price</th></tr></thead>
  <tbody>
    <tr><td>Item1</td><td>12.30</td></tr>
    <tr><td>Item2</td><td>23.40</td></tr>
    <tr><td>Item2</td><td>45.60</td></tr>
  </tbody>
</table>

https://jsfiddle.net/2b67rw5o/

期望的输出:

在此处输入图像描述

所以我不想应用.price到每个表格单元格或使用:nth-child或 jQuery .. 是否可以仅使用 css?

标签: csshtml-table

解决方案


我认为您不能在 css 中td基于应用于元素的类将类应用于元素。th

你不想使用 jQuery,但你可以使用 vanilla javascript:

const cssClass = "price";
const th = document.getElementsByClassName(cssClass)[0];
const thead = th.parentElement;
const idx = Array.prototype.indexOf.call(thead.children, th);
const tbody = th.parentElement.getElementsByTagName("tbody")[0];
Array.prototype.forEach(tbody.getElementsByTagName("tr"), tr => {
  tr.children[idx].classList.add(cssClass)
})

推荐阅读