简体   繁体   English

在HTML表格的每一行上交替CSS类

[英]Alternating the CSS class on each row of an HTML table

I have a table with a loop on a <tr> and I want to use two CSS classes for the rows, just like the attribute rowClass for rich:dataTable . 我有一个在<tr>上带有循环的表,并且我想对行使用两个CSS类,就像rich:dataTable的属性rowClass一样。

This is may part of code: 这可能是代码的一部分:

<table>
 <c:forEach items="${MyBean.Result}" var="item">
  <tr>
   <td><h:outputText value="${item.attr}" />
   </td>
  </tr>
 </c:forEach>
</table>

How can I alternate the CSS class on each row of the HTML table? 如何在HTML表格的每一行上替换CSS类?

tr.odd { background-color: #EEDDEE }
tr.even { background-color: #EEEEDD }

then use 然后用

<c:forEach items="${element}" var="myCollection" varStatus="loopStatus">
  <tr class="${loopStatus.index % 2 == 0 ? 'odd' : 'even'}">
     <td><h:outputText value="${item.attr}" />
     </td>
  </tr>
</c:forEach>

You can also use a CSS only solution: 您还可以使用纯CSS解决方案:

tr:nth-child(odd): { background-color: #EEDDEE }

and

tr:nth-child(even): { background-color: #EEEEDD }

Then you won't need to create any dynamic classes from PHP. 然后,您将不需要从PHP创建任何动态类。 Works in all browsers, except IE8 and earlier. 在除IE8和更早版本之外的所有浏览器中均可使用。

See W3Schools info 查看W3Schools信息

我的首选方法是设置一个计数器并使用MOD运算符。

<tr <cfif RowCount MOD 2 EQ 1>class="even"<cfelse>class="odd"</cfif>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM