如何使用 nth-child 对具有行跨度的表格进行样式设置?
我有一个表,其中一行使用行跨度.所以,
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 预览
相关文章