css - 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?
解决方案
我认为您不能在 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)
})
推荐阅读
- linux - ath9k 在 ocb 模式下堆叠日期
- xml - 在 Spring Boot 上接收嵌套的 xml 对象
- ui-automation - 将元素搜索限制为驱动程序 RFT
- c# - SemaphoreSlim 不阻止异步竞争条件
- mongodb - Mongodb 查询查看性能
- javascript - 保存时,Vue 生成错误错误
- javascript - 缺少我的菜单的一部分,有时不得不吃我的大部分菜单
- python - python中tensorflow的session如何初始化,保证NN模型的重现性?(层数相同但结果不同)
- sql - SQL Server 2008 迁移到 2019
- java - Databricks jdbc 驱动程序。java.lang.ClassCastExeption:无法转换为 java.lang.string