問題描述
我有一個表,其中一行使用行跨度.所以,
I have a table that has one row that uses rowspan. So,
<table>
<tr>
<td>...</td><td>...</td><td>...</td>
</tr>
<tr>
<td rowspan="2">...</td><td>...</td><td>...</td>
</tr>
<tr>
<td>...</td><td>...</td>
</tr>
<tr>
<td>...</td><td>...</td><td>...</td>
</tr>
</table>
我想使用 nth-child 偽類為每隔一行添加背景顏色,但是行跨度搞砸了;它將背景顏色添加到具有行跨度的行下方的行中,而實際上我希望它跳過該行并移至下一行.
I'd like to use the nth-child pseudo-class to add a background color to every other row, but the rowspan is messing it up; it adds the background color to the row below the row with the rowspan, when in fact I'd like it to skip that row, and move onto the next.
有沒有辦法讓 nth-child 做一些聰明的事情,或者在選擇器中使用 [rowspan] 來解決這個問題?所以在這種情況下,我希望背景顏色位于第 1 行和第 4 行,但之后位于第 6、8、10 行等等(因為這些都沒有行跨度)?這就像如果我看到一個行跨度,那么我希望 nth-child 將 1 添加到 n 然后繼續.
Is there a way to get nth-child to do something smart, or to use [rowspan] in the selector to get around this? So in this case, I'd like the background color to be on rows 1 and 4 but then after that on 6, 8, 10, and so on (since none of those have rowspans)? It's like if I see a rowspan, then I want nth-child to add 1 to n and then continue.
可能沒有解決方案,但我想我會問:-)
Probably no solution to this, but thought I'd ask :-)
推薦答案
不幸的是,單獨使用 :nth-child()
或單獨使用 CSS 選擇器無法做到這一點.這與 :nth-child()
的性質有關,它純粹基于作為其父元素的第 n 個子元素進行選擇,以及與 CSS 缺少父選擇器(只有在沒有的情況下才能選擇 tr
t 包含一個 td[rowspan]
,例如).
Unfortunately, there's no way to do this with :nth-child()
alone, or by using CSS selectors alone for that matter. This has to do with the nature of :nth-child()
which selects purely based on an element being the nth child of its parent, as well as with CSS's lack of a parent selector (you can't select a tr
only if it doesn't contain a td[rowspan]
, for example).
jQuery 確實有 CSS 缺少的 :has()
選擇器,但是您可以將它與 :even
結合使用(而不是 :odd
因為它是 0-indexed 而不是 :nth-child()
的 1-index) 用于過濾作為 CSS 的替代方案:
jQuery does have the :has()
selector that CSS lacks, though, which you can use in conjunction with :even
(not :odd
as it's 0-indexed versus :nth-child()
's 1-index) for filtering as an alternative to CSS:
$('tr:not(:has(td[rowspan])):even')
jsFiddle 預覽
這篇關于如何使用 nth-child 對具有行跨度的表格進行樣式設置?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!