根据值更改表格的背景单元格 [英] Changing background cell of table depending on value

查看:93
本文介绍了根据值更改表格的背景单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的站点读取一个XML文件,该文件包含数据表的信息(值). 我使用CSS设置表格的样式,一切正常.

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.

为了获得更好的用户体验,我想知道是否可以根据其值动态更改每个单元格的背景颜色?

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?

例如:

每个数字小于"5"的单元格都有红色背景色;

Each cell that contains a number less then "5" has a red background color;

每个单元格> ="5"具有绿色背景.

each cell >= "5" has a green background color.

我对此的第一个解决方案是使用Javascript-但我想知道是否有办法仅使用CSS样式来解决此问题?

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?

推荐答案

使用 just CSS不可能做到这一点(尽管您可以使用JavaScript分配类以使其能够通过CSS部分实现).要使用纯JavaScript而不是库,请执行以下操作:

This isn't possible with just CSS (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:

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';
    }
}

JS Fiddle演示.

或者,使用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';
    }
}

JS Fiddle演示.

参考文献:

  • className.
  • getElementById().
  • getElementsByTagName().
  • innerHTML.
  • parseInt().
  • style.

这篇关于根据值更改表格的背景单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆