更改 google 时间线图表行中的背景颜色

Change background color in a google timeline chart row

参考:https://developers.google.com/chart/interactive/docs/gallery/timeline#a-simple-example

在上面的图表中,交替的行有背景色。 亚当斯是灰色的,而华盛顿和杰斐逊是白色的。 我想根据与该行相关的数据值之一为背景着色。

没有更改行背景颜色的标准选项。

但可以在图表的 'ready' 事件中手动更改颜色。

背景行将使用 <rect> 个元素绘制。
当事件触发时,通过测试以下属性找到元素。

x - 所有值都将为零 --> x="0"
stroke - 只有整体背景<rect>才会有除"none"

以外的描边属性

然后将 fill 属性设置为您选择的颜色。

  // make sure rect is a background row
  if ((rect.getAttribute('x') === '0') && (rect.getAttribute('stroke') === 'none')) {
    // determine existing color
    if (rect.getAttribute('fill') === '#ffffff') {
      rect.setAttribute('fill', 'cyan');
    } else {
      rect.setAttribute('fill', 'magenta');
    }
  }

请参阅以下工作片段...

google.charts.load('current', {
  packages: ['timeline']
}).then(function () {
  var container = document.getElementById('chart');
  var chart = new google.visualization.Timeline(container);
  var dataTable = new google.visualization.DataTable();

  dataTable.addColumn({type: 'string', id: 'President'});
  dataTable.addColumn({type: 'date', id: 'Start'});
  dataTable.addColumn({type: 'date', id: 'End'});
  dataTable.addRows([
    ['Washington', new Date(1789, 3, 30), new Date(1797, 2, 4)],
    ['Adams',      new Date(1797, 2, 4),  new Date(1801, 2, 4)],
    ['Jefferson',  new Date(1801, 2, 4),  new Date(1809, 2, 4)]
  ]);

  google.visualization.events.addListener(chart, 'ready', function () {
    var rects = container.getElementsByTagName('rect');
    Array.prototype.forEach.call(rects, function(rect) {
      // make sure rect is a background row
      if ((rect.getAttribute('x') === '0') && (rect.getAttribute('stroke') === 'none')) {
        // determine existing color
        if (rect.getAttribute('fill') === '#ffffff') {
          rect.setAttribute('fill', 'cyan');
        } else {
          rect.setAttribute('fill', 'magenta');
        }
      }
    });
  });

  chart.draw(dataTable);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>