如何有条件地为表格单元格中的背景着色? [英] How do I conditionally color the background in a table cell?
问题描述
我正在使用 p:dataTable (PrimeFaces)渲染表格,我要做的是根据单元格内容的值为单元格的背景着色.这与为行或列着色不同-它是单个单元格.
I am rendering a table with p:dataTable (PrimeFaces) and what I want to do is color the background of cells depending on the value of their content. This is different from coloring a row or a column -- it is the individual cell.
首先是CSS问题.如果我这样做:
First a CSS problem. If I do this:
<p:column headerText="xyzzy">
<div style="background-color: green">
<h:outputText value="#{rowVar.anumber}" >
<f:convertNumber groupingUsed="true" />
</h:outputText>
</div>
</p:column>
仅设置内容的背景色,而不是设置整个单元格的背景色.换句话说,填充仍然是默认设置.
the background color just of the content gets set, not the whole cell. In other words the padding is still the default.
第二,我想使 style 字符串成为变量表达式.我可以向后备Bean中添加一个函数,但是如何访问方法中的表内容?这样行吗?
Second, I want to make the style string a variable expression. I can add a function to the backing bean, but how do I access the table content in the method? Will this work?
<div style="#{bean.computeCSS(rowVar.number}">
我想出了一种做条件部分的方法,但是我仍然需要CSS部分的帮助.我的解决方案如下:
I figured out a way to do the conditional part, but I still need help with the CSS part. My solution looks like:
<p:column headerText="xyzzy">
<div class="#{rowVar.anumber gt 0 ? 'colored' : ''}">
<h:outputText value="#{rowVar.anumber}">
<f:convertNumber groupingUsed="true" />
</h:outputText>
</div>
</p:column>
虽然我不喜欢EL,但是这样做的好处是不需要后备bean方法.
Although I dislike getting to fancy in EL, this has the advantage of not needed a backing bean method.
但是,我仍然只获得背景颜色设置,而不是整个单元格设置.
However I still only get the background color set, not the whole cell.
推荐答案
您也可以将css类添加到行和列中,以标识一个单元格.
使用dataTable的rowStyleClass
属性(示例).
如果要为多行着色:
You can add a css class to the row and to the column too, that identifies a cell.
Use the dataTable's rowStyleClass
attribute (example).
If you want to color multiple rows:
<p:dataTable value="#{bean.rows}" var="rowVar"
rowStyleClass="#{rowVar.firstCol gt 0 ? 'firstColColored' : ''}
#{rowVar.secondCol gt 0 ? 'secondColColored' : ''}">
<p:column styleClass="firstCol">...
<p:column styleClass="secondCol">
css:
.firstColColored .firstCol {
background: pink;
}
这篇关于如何有条件地为表格单元格中的背景着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!