4

我有一个表,每列的值都在 -100 到 +100 之间。我想用所有低于零到-100的元素为它们着色,从白色到深红色。从零到+100的颜色从白色到深绿色。

关于如何使用 JQuery 酿造颜色的任何建议?

我在使用选择器时遇到了问题..所以最好我可以通过 jquery 设置背景 css

谢谢你。

4

4 回答 4

5

使用可以计算两个值之间的点的颜色分量的函数,您可以使用rgb(r,g,b)CSS 中的颜色语法来设置背景颜色:

function morph(start, stop, point) {
  return Math.round(stop - start) * point / 100 + start);
}

$('td').each(function(){
  var value = parseInt($(this).text());
  var color;
  if (value < 0) {
    color = morph(255,100,-value) + ',' + morph(255,0,-value) + ',' + morph(255,0,-value);
  } else {
    color = morph(255,0,value) + ',' + morph(255,50,value) + ',' + morph(255,0,value);
  }
  $(this).css('background-color', 'rgb(' + color + ')');
});
于 2011-04-10T16:05:14.457 回答
4

我可以推荐我自己的 jQuery 插件吗?

jQuery Hottie使得使用普通标记和添加背景颜色变得容易,如下所示:

<table id="myTable">
    <tr><td>-100</td><td>50</td><td>-30</td></tr>
    <tr><td>100</td><td>0</td><td>-30</td></tr>
    <tr><td>750</td><td>-50</td><td>40</td></tr>
</table>

在 JS 中:

$("#myTable td").hottie({
    colorArray : [ 
        "#F8696B", // highest value
        "#FFFFFF",
        "#63BE7B"  // lowest value
        // add as many colors as you like...
    ]
});

结果:

JSFiddle

在JSFiddle中查看此示例

于 2013-07-25T22:06:45.363 回答
1

您可以考虑使用HeatColor jQuery 插件。但是,请注意,您想要的精确颜色序列可能不可用。

可以在 designchemical.com 上找到关于自己滚动的一个很好的教程。

于 2011-11-14T17:31:12.770 回答
0

我在需要具有不同级别的绿色(最高值)和红色(最低值)的任何表上使用以下函数。

(在这个例子中,td 值是代表百分比的浮点数——比如 0.941 代表 94.1%):

function heatmap()
{
    var heat_max = 0;
    var heat_min = 100;

    //loop through table cells to find min and max values
    $('table#heatmap').find('td').each(function() 
    {
        var cell_val = Math.round(parseFloat($(this).text()) * 1000) / 10;

        if(cell_val > heat_max) { heat_max = cell_val;}
        if(cell_val < heat_min) { heat_min = cell_val;}
    });

    //reloop through table cells and apply background color
    $('table#heatmap').find('td').each(function()
    {
        var cell_val = Math.round(parseFloat($(this).text()) * 1000) / 10;

        var color_pct = (cell_val - heat_min)  / (heat_max - heat_min);
        var color_int = 2 * 255 * color_pct;

        var r = 255, g = 255;
        if(color_int <= 255) { g = color_int;        } 
                       else  { r =  510 - color_int; }

        var bg_color = 'rgba('+r+', '+g+', 50, 0.2)';

        $(this).css({'backgroundColor' : bg_color});
    });

}
于 2020-01-06T08:55:11.127 回答