带有隐藏行的HTML表格备用行颜色

我正在尝试用行的替代颜色编写简单的表。

这是非常直接的,已经达到了预期的结果,我面临的问题是当我有一个隐藏的行时,颜色模式会遇到问题。

这是我的小提琴: http : //jsfiddle.net/oampz/2Wt49/

如您所见,当您单击“+”时,表格会展开并且行颜色会交替显示,但是当表格折叠时,颜色会出现问题。

这是我的HTML:

Name Age Height Weight
+ 0000111 0000111 0000111 0000111
0000222 0000222 0000222 0000222
0000333 0000333 0000333 0000333
0000444 0000444 0000444 0000444

这是我的CSS:

 table { border-collapse: collapse; border-spacing: 0; width: 100%; } th { min-width: 22px; } .stripes tbody > tr:nth-child(2n+2) { background: #f2f2f2; } .stripes li:nth-child(2n+2) { background: #f2f2f2; } .tbl { border: 1px solid #d1d1d1; font-size: 12px; font-size: 0.75rem; line-height: 2; clear: both; } .tbl th, .tbl td { padding: 3px; text-align: left; border-right: 1px solid #d1d1d1; } .tbl th { border-bottom: 1px solid #d1d1d1; } .tbl--highlight tbody tr:hover { background: #d4e8fc; cursor: pointer; } .tbl--input td { overflow: hidden; } .half-mb { margin: 0 0 12px 0; } .visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } 

任何帮助赞赏。

目前似乎没有针对纯CSS的解决方案。 nth-child工作正常。 桌子上有儿童 – 可见与否。 所以你需要一个javascript解决方案。 我已经更新了你的小提琴: http : //jsfiddle.net/2Wt49/9/

它正在实现一个jQuery函数,如下所示:

  function stripeTable(){ $("table.stripes tr").removeClass("odd"); $("table.stripes tr:visible:odd").addClass("odd"); } 

我已经对你的jsfiddle例子进行了一些修改并让它工作了……

http://jsfiddle.net/2Wt49/10/

我添加了以下function……

 function setRowClasses() { $("#bs-search-results tbody tr") .removeClass("even") .filter(function() { return $(this).height() != 1; }) .each(function(i) { if (i % 2 == 0) $(this).addClass("even"); }); } 

这为每个偶数编号的可见行设置了一个类,它是影响样式的类,而不是使用css来确定它是奇数行还是偶数行。

然后,当您切换表中的任何行时,该函数需要被调用onload / onready。

出于好奇,有没有一个原因你不只是设置visuallyhidden display:none

nth-childnth-of-type伪类将始终计算所有元素,无论它们是否可见。 我可以想到两种方法来实现隐藏行的斑马条纹:

  1. 在行中添加类名,使用JavaScript在显示或隐藏行时调整类名。
  2. 在整个表格上使用重复的条纹背景,每个条纹与表格行的高度相同。

试试这个,

这是演示http://jsfiddle.net/dhana36/2Wt49/14/

 $(".ShowMe").click(function() { $("#itsHidden").toggleClass("visuallyhidden"); $("#itsHidden2").toggleClass("visuallyhidden"); $('tbody tr').not('.visuallyhidden').each(function(index,el){ if(index%2 != 0){ $(this).css('background','#f2f2f2') } else{ $(this).css('background','#fff') } }); });