如何为相同元素的表格单元格组着色

发布于 2025-01-04 16:15:19 字数 1081 浏览 0 评论 0原文

对于包含数字的 HTML 表格,我正在寻找一种优雅的 JavaScript/CSS 方法来识别每列中相等值的组,并相应地为相应单元格的背景着色。我将在回归测试结果的网络演示中使用它。

在 python 中,我可能会使用类似 itertools.groupby() 的东西。

为了说明这一点,我提供了一个屏幕截图示例和相应的 HTML 代码(手动构建)。

<head>
  <style>
    td {font-family: Monospace; font-size:16; }
  </style>
</head>

<body>
  <table border=1>
    <tr><td>1.111</td></tr>
    <tr><td>1.111</td></tr>
    <tr><td bgcolor="LightBlue">2.222</td></tr>
    <tr><td>1.111</td></tr>
    <tr><td bgcolor="LightBlue">2.222</td></tr>
    <tr><td> 1.111</td></tr>
    <tr><td bgcolor="LightBlue">2.222</td></tr>
    <tr><td bgcolor="Goldenrod">3.333</td></tr>
    <tr><td> 1.111</td></tr>
  </table>
</body>

在此处输入图像描述

For an HTML table with numbers, I am looking for an elegant JavaScript/CSS way to identify groups of equal values in each column, and color the background of corresponding cells accordingly. I will use it in a web presentation of regression test results.

In python I would probably have used something like itertools.groupby().

To illustrate, I include a screenshot example and the corresponding HTML code (constructed manually).

<head>
  <style>
    td {font-family: Monospace; font-size:16; }
  </style>
</head>

<body>
  <table border=1>
    <tr><td>1.111</td></tr>
    <tr><td>1.111</td></tr>
    <tr><td bgcolor="LightBlue">2.222</td></tr>
    <tr><td>1.111</td></tr>
    <tr><td bgcolor="LightBlue">2.222</td></tr>
    <tr><td> 1.111</td></tr>
    <tr><td bgcolor="LightBlue">2.222</td></tr>
    <tr><td bgcolor="Goldenrod">3.333</td></tr>
    <tr><td> 1.111</td></tr>
  </table>
</body>

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

逐鹿 2025-01-11 16:15:19

我可以想到这样的

var lookup = Object.create( null );

Array.prototype.forEach.call( document.querySelectorAll('table td'), function( td ) {
    var id = td.textContent.trim();

    if( typeof lookup[ id ] === 'undefined' ) {
        lookup[ id ] = [ td ];
    }
    else {
        lookup[ id ].push( td );
    }
});

Object.keys( lookup ).forEach(function( name ) {
    if( lookup[ name ] && lookup[ name ].length ) {
        var rnd = 'rgba(red,green,blue,1)'
            .replace( 'red', ~~(Math.random() * 255) )
            .replace( 'green', ~~(Math.random() * 255) )
            .replace( 'blue', ~~(Math.random() * 255) );

        lookup[ name ].forEach(function( td ) {
            td.style.backgroundColor = rnd;
        });
    }
});

演示: http://jsfiddle.net/ch6qZ/1/

A新的警告:上面的代码严重依赖于 ES5,因此如果您想使用它,请确保您还在网站上加载了适用于旧浏览器的 ES5-Shim 库。另外,querySelectorAll 的选择器应该更加具体,最好的情况是您可以为该表提供一个 id。最后,在此示例中,颜色生成是根据 Math.random() 进行的,您可能希望自己定义颜色。


此示例代码创建一个空对象并将其用作哈希。可用的 td 值作为键名创建一次,每个键的值是共享相同文本内容的 td 数组。完成后,我们循环该哈希并为每个 td 组设置随机背景颜色。

I could think of something like this

var lookup = Object.create( null );

Array.prototype.forEach.call( document.querySelectorAll('table td'), function( td ) {
    var id = td.textContent.trim();

    if( typeof lookup[ id ] === 'undefined' ) {
        lookup[ id ] = [ td ];
    }
    else {
        lookup[ id ].push( td );
    }
});

Object.keys( lookup ).forEach(function( name ) {
    if( lookup[ name ] && lookup[ name ].length ) {
        var rnd = 'rgba(red,green,blue,1)'
            .replace( 'red', ~~(Math.random() * 255) )
            .replace( 'green', ~~(Math.random() * 255) )
            .replace( 'blue', ~~(Math.random() * 255) );

        lookup[ name ].forEach(function( td ) {
            td.style.backgroundColor = rnd;
        });
    }
});

Demo: http://jsfiddle.net/ch6qZ/1/

A new words of caution: The above code heavily relies on ES5, so if you want to use it make sure you've also loaded an ES5-Shim library on your site for old'ish browsers. Also, the selector for querySelectorAll should be way more specific, best case scenario you can give that table an id. Lastly color generation happens per Math.random() in this example, you might want to define colors on your own.


This example code creates an empty object and uses it as a hash. Available td values are created once as keyname and the value for each key is an array of td's which share the same text content. After that is done, we loop over that hash and set a random background-color for each td-group.

飘然心甜 2025-01-11 16:15:19

这是一个纯 JavaScript 解决方案(使用 jsFiddle),适用于您发布的示例源:

function colorTableCells() {
    'use strict';
    var i = 0; //counter variable
    var j = 0; //counter variable
    var k = 0; //counter variable
    var m = 0; //counter variable
    var n = 0; //counter variable
    var tables = document.getElementsByTagName('table'); //All tables as a collection.
    var rows = []; //table rows collection, needed to determine columns
    var cells = []; //td collection
    var cell = {}; //used first as a Cell object (custom, see below) and then as a td (after all unique values by column have been determined
    var values = []; //array of Cell objects (custom, see below).
    var columnColorMap = {
        'column0': 'gray',
        'column1': 'purple',
        'column2': 'pink',
        'column3': 'mint',
        'column4': 'cyan'
    }; //columnColorMap holds the shade with which to color the column.
    var C = function () {
        //Cell Object, holds properties unique to the cells for coloring
        this.value = 0; //Cell value
        this.color = {
            'red': 255,
            'green': 255,
            'blue': 255
        }; //Cell color, determined by column
        this.shades = {
            'gray': [this.color.red, this.color.green, this.color.blue],
            'purple': [this.color.red, this.color.green],
            'pink': [null, this.color.green, this.color.blue],
            'mint': [this.color.red, , this.color.blue],
            'cyan': [this.color.red],
            'magenta': [null, this.color.green],
            'yellow': [null, null, this.color.blue]
        }; //A quick way to determine the shade for the column. It holds color values to modify (and always in RGB order) or a null value if R, G, or B should be left alone.
        this.column = 0; //Column the cell is in, relative to the table it is in.
        this.darken = function (stepValue, hue) {
            //function that returns a new color, based on the hue that is passed in
            var decrement = 8;
            var i = 0;
            var ret = {
                'red': 255,
                'green': 255,
                'blue': 255
            };
            if (!stepValue) {
                stepValue = 0;
            }
            decrement = decrement * stepValue;
            for (i = 0; i < hue.length; i += 1) {
                if (hue[i]) {
                    hue[i] = hue[i] - decrement;
                }
            }
            if (hue[0]) {
                ret.red = hue[0];
            }
            if (hue[1]) {
                ret.green = hue[1];
            }
            if (hue[2]) {
                ret.blue = hue[2];
            }
            return ret;
        };
        this.getHexBackgroundColorString = function () {
            //returns `rbg(val, val, val) as '#RRGGBB'
            var s = '';
            var red = this.color.red.toString(16);
            var green = this.color.green.toString(16);
            var blue = this.color.blue.toString(16);
            if (red.length < 2) {
                red = '0' + red;
            }
            if (green.length < 2) {
                green = '0' + green;
            }
            if (green.length < 2) {
                blue = '0' + blue;
            }
            s = '#' + red + green + blue;
            return s.toUpperCase();
        };
    };
    var colHasValue = function (array, cell) {
        //loop through array, returns 'if cell.value && cell.column are found or otherwise'
        var i = 0;
        var found = false;
        for (i = 0; i < array.length; i += 1) {
            if (array[i].value === cell.value && array[i].column === cell.column) {
                found = true;
                i = array.length;
            }
        }
        return found;
    };
    for (i = 0; i < tables.length; i += 1) {
        cells = tables[i].getElementsByTagName('td'); //get all td elements per table
        for (j = 0; j < cells.length; j += 1) {
            cell = new C(); //grab a new Cell object
            cell.value = parseFloat(cells[j].innerText); //capture cell value
            cell.column = cells[j].cellIndex; //capture cell column
            if (!colHasValue(values, cell)) {
                //hasn't been previously stored yet, so darken according to column and store
                cell.color = cell.darken(j, cell.shades[columnColorMap['column' + cell.column.toString()]]);
                values.push(cell); //capture all unique values
            }
        }
        rows = tables[i].getElementsByTagName('tr'); //grab all rows by table
        for (k = 0; k < rows.length; k += 1) {
            //start looping through all the rows
            for (m = 0; m < rows[k].childNodes.length; m += 1) {
                //start looping through all of the row's children
                if (rows[k].childNodes[m].nodeName.toLowerCase() === 'td') {
                    cell = rows[k].childNodes[m]; //found a td element, alias to cell for easier use
                    for (n = 0; n < values.length; n += 1) {
                        //loop through stored cell values
                        if (parseFloat(cell.innerText) === values[n].value && cell.cellIndex === values[n].column) {
                            //value and column matches
                            cell.style.backgroundColor = values[n].getHexBackgroundColorString(); //set background-color
                            n = values.length; //exit for
                        }
                    }
                }
            }
        }
    }
}
colorTableCells();

修改任何(或全部) ) 来更改颜色:

  • shades 集合
  • columnColorMap 对象
  • darken 函数

Here's a pure JavaScript solution (with jsFiddle) that works on your posted sample source:

function colorTableCells() {
    'use strict';
    var i = 0; //counter variable
    var j = 0; //counter variable
    var k = 0; //counter variable
    var m = 0; //counter variable
    var n = 0; //counter variable
    var tables = document.getElementsByTagName('table'); //All tables as a collection.
    var rows = []; //table rows collection, needed to determine columns
    var cells = []; //td collection
    var cell = {}; //used first as a Cell object (custom, see below) and then as a td (after all unique values by column have been determined
    var values = []; //array of Cell objects (custom, see below).
    var columnColorMap = {
        'column0': 'gray',
        'column1': 'purple',
        'column2': 'pink',
        'column3': 'mint',
        'column4': 'cyan'
    }; //columnColorMap holds the shade with which to color the column.
    var C = function () {
        //Cell Object, holds properties unique to the cells for coloring
        this.value = 0; //Cell value
        this.color = {
            'red': 255,
            'green': 255,
            'blue': 255
        }; //Cell color, determined by column
        this.shades = {
            'gray': [this.color.red, this.color.green, this.color.blue],
            'purple': [this.color.red, this.color.green],
            'pink': [null, this.color.green, this.color.blue],
            'mint': [this.color.red, , this.color.blue],
            'cyan': [this.color.red],
            'magenta': [null, this.color.green],
            'yellow': [null, null, this.color.blue]
        }; //A quick way to determine the shade for the column. It holds color values to modify (and always in RGB order) or a null value if R, G, or B should be left alone.
        this.column = 0; //Column the cell is in, relative to the table it is in.
        this.darken = function (stepValue, hue) {
            //function that returns a new color, based on the hue that is passed in
            var decrement = 8;
            var i = 0;
            var ret = {
                'red': 255,
                'green': 255,
                'blue': 255
            };
            if (!stepValue) {
                stepValue = 0;
            }
            decrement = decrement * stepValue;
            for (i = 0; i < hue.length; i += 1) {
                if (hue[i]) {
                    hue[i] = hue[i] - decrement;
                }
            }
            if (hue[0]) {
                ret.red = hue[0];
            }
            if (hue[1]) {
                ret.green = hue[1];
            }
            if (hue[2]) {
                ret.blue = hue[2];
            }
            return ret;
        };
        this.getHexBackgroundColorString = function () {
            //returns `rbg(val, val, val) as '#RRGGBB'
            var s = '';
            var red = this.color.red.toString(16);
            var green = this.color.green.toString(16);
            var blue = this.color.blue.toString(16);
            if (red.length < 2) {
                red = '0' + red;
            }
            if (green.length < 2) {
                green = '0' + green;
            }
            if (green.length < 2) {
                blue = '0' + blue;
            }
            s = '#' + red + green + blue;
            return s.toUpperCase();
        };
    };
    var colHasValue = function (array, cell) {
        //loop through array, returns 'if cell.value && cell.column are found or otherwise'
        var i = 0;
        var found = false;
        for (i = 0; i < array.length; i += 1) {
            if (array[i].value === cell.value && array[i].column === cell.column) {
                found = true;
                i = array.length;
            }
        }
        return found;
    };
    for (i = 0; i < tables.length; i += 1) {
        cells = tables[i].getElementsByTagName('td'); //get all td elements per table
        for (j = 0; j < cells.length; j += 1) {
            cell = new C(); //grab a new Cell object
            cell.value = parseFloat(cells[j].innerText); //capture cell value
            cell.column = cells[j].cellIndex; //capture cell column
            if (!colHasValue(values, cell)) {
                //hasn't been previously stored yet, so darken according to column and store
                cell.color = cell.darken(j, cell.shades[columnColorMap['column' + cell.column.toString()]]);
                values.push(cell); //capture all unique values
            }
        }
        rows = tables[i].getElementsByTagName('tr'); //grab all rows by table
        for (k = 0; k < rows.length; k += 1) {
            //start looping through all the rows
            for (m = 0; m < rows[k].childNodes.length; m += 1) {
                //start looping through all of the row's children
                if (rows[k].childNodes[m].nodeName.toLowerCase() === 'td') {
                    cell = rows[k].childNodes[m]; //found a td element, alias to cell for easier use
                    for (n = 0; n < values.length; n += 1) {
                        //loop through stored cell values
                        if (parseFloat(cell.innerText) === values[n].value && cell.cellIndex === values[n].column) {
                            //value and column matches
                            cell.style.backgroundColor = values[n].getHexBackgroundColorString(); //set background-color
                            n = values.length; //exit for
                        }
                    }
                }
            }
        }
    }
}
colorTableCells();

Modify any (or all) of the following to change the colors:

  • The shades collection
  • The columnColorMap object
  • The darken function
橘和柠 2025-01-11 16:15:19

你可以使用 Jquery,

$("td:contains('2.222')").css("background-color","LightBlue");
$("td:contains('3.333')").css("background-color","Goldenrod");

you can with Jquery,

$("td:contains('2.222')").css("background-color","LightBlue");
$("td:contains('3.333')").css("background-color","Goldenrod");
追星践月 2025-01-11 16:15:19

假设该值为十进制数,则可以用除以%10的商来提取颜色。

颜色选择功能

    choiceColor (value) {
        let colors = ['red', 'pink', 'purple', 'indigo', 'blue', 'light-blue', 'cyan', 'teal', 'green', 'lime']
        return colors[value % 10]
    }

Assuming that value is a decimal number, you can extract the color with the quotient divided by % 10.

color choice function

    choiceColor (value) {
        let colors = ['red', 'pink', 'purple', 'indigo', 'blue', 'light-blue', 'cyan', 'teal', 'green', 'lime']
        return colors[value % 10]
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文