找不到任何東西,所以這是我的標記:
<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>

所以我不想應用于.price每個表格單元格或使用:nth-child或 jQuery .. 僅使用 css 可能嗎?
uj5u.com熱心網友回復:
我認為您不能td根據應用于元素的類th在 css中將類應用于元素。
你不想使用 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)
})
uj5u.com熱心網友回復:
我不認為你想做的事情在今天的 CSS 中是可能的。盡管經常被請求,但您不能(至少現在)使用 CSS 選擇器遍歷父級,因為 CSS 無法在 DOM 層次結構中向上傳遞資訊。但是,此特定功能將是確定需要樣式化的以下行中子項索引的最低要求。
有關更多資訊,請參閱“是否有 CSS 父選擇器?”的答案。,其中說明“目前無法在 CSS 中選擇元素的父級。(...) 也就是說,選擇器級別 4 作業草案包括一個 :has() 偽類,它將提供此功能。”
使用當前的草稿,:has()您至少可以構建一個重復的 CSS 解決方案,其列數有限,如下所示:
/* For a column of three columns maximum: */
/* if price is first column */
table:has(thead > th.price:first-child) tbody > td:first-child,
/* if price is second column */
table:has(thead > :first-child th.price) tbody > :first-child td,
/* if price is third column */
table:has(thead > :first-child * th.price) tbody > :first-child * td {
...
}
糟糕,我知道……但目前在可預見的未來是唯一的原生 CSS 解決方案。
但是現在,根據您的需要,您還可以“作弊”:如果應更改列的背景和/或邊框,您只能使用th標題單元格的樣式(例如,通過濫用:before和:after)。但是如果沒有 JavaScript,文本內容的特定更改將是不可能的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/326589.html
標籤:css html-table
