CSS 根据值更改表格的背景单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8666500/
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
Changing background cell of table depending on value
提问by Stone
My site reads a XML file that contains information (values) for a data-table. I use CSS to style the table and everything works fine.
我的站点读取包含数据表信息(值)的 XML 文件。我使用 CSS 来设置表格的样式,一切正常。
To get a better user-experience I wondered if it is possible to change the background color of each cell dynamically depending on its value?
为了获得更好的用户体验,我想知道是否可以根据每个单元格的值动态更改其背景颜色?
For example:
例如:
Each cell that contains a number less then "5" has a red background color;
每个包含小于“5”的数字的单元格具有红色背景色;
each cell >= "5" has a green background color.
每个单元格 >= "5" 都有绿色背景色。
My first solution on this is to use Javascript - but I want to know if there is a way to solve this with CSS-styles only?
我对此的第一个解决方案是使用 Javascript - 但我想知道是否有办法仅使用 CSS 样式来解决这个问题?
回答by David says reinstate Monica
This isn't possible with justCSS (though you can use JavaScript to assign classes to enable it to be partially implemented with CSS). To use plain JavaScript, rather than a library:
仅使用CSS是不可能的(尽管您可以使用 JavaScript 分配类以使其能够使用 CSS 部分实现)。要使用纯 JavaScript 而不是库:
var table = document.getElementById('tableID');
var tbody = table.getElementsByTagName('tbody')[0];
var cells = tbody.getElementsByTagName('td');
for (var i=0, len=cells.length; i<len; i++){
if (parseInt(cells[i].innerHTML,10) > 5){
cells[i].style.backgroundColor = 'red';
}
else if (parseInt(cells[i].innerHTML,10) < -5){
cells[i].style.backgroundColor = 'green';
}
}
Or, to use CSS classes:
或者,使用 CSS 类:
var table = document.getElementById('tableID');
var tbody = table.getElementsByTagName('tbody')[0];
var cells = tbody.getElementsByTagName('td');
for (var i=0, len=cells.length; i<len; i++){
if (parseInt(cells[i].innerHTML,10) > 5){
cells[i].className = 'red';
}
else if (parseInt(cells[i].innerHTML,10) < -5){
cells[i].className = 'green';
}
}
References:
参考:
回答by vanzylv
Not to sure about css.I'll jump straight to jquery
不确定css。我会直接跳到jquery
$('#mytable tr td').each(function(){
if($(this).text() > 5)$(this).css('background-color','red');
});
回答by Karan Singh
without loop you can do it this way
没有循环,你可以这样做
var val="ff";
var val="ff";
$("#grid td:contains('"+val+"')").css('background-color', 'red');
$("#grid td:contains('"+val+"')").css('background-color', 'red');
回答by Noah McIlraith
It may be possible to do this using CSS expressions, but this is non-standard and IIRC only works in Internet Explorer. So I'd advise against it.
或许可以使用 CSS 表达式来做到这一点,但这是非标准的,而且 IIRC 仅适用于 Internet Explorer。所以我建议不要这样做。
Doing this server-side or using JavaScript are your best bets.
在服务器端执行此操作或使用 JavaScript 是您最好的选择。