使css的nth-child()仅影响可见元素

45
有没有一种方法可以只对可见元素使用这个 CSS?
table.grid tr.alt:nth-child(odd)
{
    background:#ebeff4;
}

table.grid tr.alt:nth-child(even)
{
    background:#ffffff;
}
如果我使用 $('select some tr:s').hide() 来隐藏一些行,那么我会得到奇偶样式混合的输出。

4
你考虑过在 $().hide() 后重新应用 CSS,使用 $('.alt:visible:even') 和 $('alt:visible:odd') 吗? - Rodaine
3个回答

20

在 Rodaine 在评论中建议的解决方案后,最终我使用了它。在显示/隐藏之后,我执行以下操作:

$('.alt:visible:odd').css('background', '#EBEFF4');
$('.alt:visible:even').css('background', '#FFFFFF'); 

在我的情况下,设置背景色破坏了我的悬停效果,使用!important解决了这个问题,让悬停背景色保持不变。

table.grid tr.hover:hover
{
    cursor:pointer;
    background:#D2E0E9 !important;    
}

4
在生产环境中使用 !important 不是一个好习惯。如果你最终使用了 !important,那么这意味着解决方案可能会更加复杂,但它是存在的。在这种情况下,你可以使用 jQuery 应用类别,以便仍然能够悬停而不需要使用 !important:http://codepen.io/gfra/pen/nFrEc - Gfra54
有时在使用外部库时,你没有任何选择,只能使用"!important"。 - LarryBud

-2
另一个选择是在隐藏其他元素时,将类应用于可见元素。将nth-child应用于此类(仅应用于可见元素)。
在这种情况下,您不必使用!important标签来保持悬停背景。

很遗憾,这是不可能的:https://dev59.com/bW035IYBdhLWcg3wbPY5 - Christoffer

-5

你可以这样做:

$('some_selector tr:visible').hide()

希望这能有所帮助


1
这不是我的问题所在。 - Andreas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接