通过 XSL 具有交替行颜色的 HTML 表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/469917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML table with alternating row colors via XSL
提问by JoelB
What is the easiest way to alternate row colors in an HTML table (a.ka. striping). Most of my tables are created in XSL templates like the following, with the table, thead, etc.. defined in another template.
在 HTML 表中交替行颜色的最简单方法是什么(又名条纹)。我的大部分表格都是在 XSL 模板中创建的,如下所示,表格、thead 等在另一个模板中定义。
<xsl:template match="typ:info">
<tr>
<td>
<xsl:value-of select="typ:dateAccessed" />
</td>
<td>
<xsl:value-of select="typ:loginId" />
</td>
</tr>
</xsl:template>
My preference is to use alternating classes on the elements.
我的偏好是在元素上使用交替类。
回答by Tomalak
If you must produce hard-coded colors in HTML:
如果您必须在 HTML 中生成硬编码颜色:
<xsl:template match="typ:info">
<xsl:variable name="css-class">
<xsl:choose>
<xsl:when test="position() mod 2 = 0">even</xsl:when>
<xsl:otherwise>odd</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<tr class="{$css-class}">
<td>
<xsl:value-of select="typ:dateAccessed" />
</td>
<td>
<xsl:value-of select="typ:loginId" />
</td>
</tr>
</xsl:template>
With today's browsers you are much better off using CSS and tr:nth-child(odd)
.
对于当今的浏览器,您最好使用 CSS 和tr:nth-child(odd)
.
This results in less hassle on the XSLT side, much cleaner HTML markup - and it's compatible with client-side table sorting and -filtering.
这会减少 XSLT 方面的麻烦,更清晰的 HTML 标记 - 并且它与客户端表格排序和过滤兼容。
回答by Gerben
You could also use css3.
您也可以使用 css3。
tr:nth-child(odd) { background: #ff0000; }
Supported as of IE9 an for quite some time by all the other browsers.
从 IE9 开始,所有其他浏览器都支持了很长一段时间。
回答by Wolfwyrd
Use an XSL:When and compare position mod 2 to get odd or even rows to alter classes when needed like:
使用 XSL:When 并比较位置 mod 2 以获得奇数或偶数行以在需要时更改类,例如:
<xsl:choose>
<xsl:when test="position() mod 2 = 1">
<td class="odds">blah</td>
</xsl:when>
<xsl:otherwise>
<td class="even">blah</td>
</xsl:otherwise>
</xsl:choose>
EDIT:Getting my odd/even the right way around sigh
编辑:让我的奇数/偶数以正确的方式叹息
回答by Juan Zamora
May we want to change only the class name instead, when can choose inside a variable to enable change its inner value. Something like this:
可能我们只想改变类名,什么时候可以选择一个变量内部来启用改变它的内部值。像这样的东西:
<xsl:variable name="myDemoClass" >
<xsl:choose>
<xsl:when test="position() mod 2 = 0">
<xsl:text>myDemoClass</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:text>myDemoClass otherClass</xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
With this, we are able to change the variable name and then we can change for example, a div class content.
有了这个,我们就可以更改变量名称,然后我们可以更改例如 div 类的内容。
<div class="{$myDemoClass}">
Regards!
问候!