You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Timeline Chart中使用jQuery按fill填充色筛选rect矩形元素

问题原因

代码不生效主要是两个核心问题:

  • 执行时机错误:Google Timeline图表为异步渲染,若在页面加载阶段直接执行选择器操作,此时<rect>元素还未被渲染到DOM中,自然无法匹配到目标元素。
  • 颜色值格式不匹配:通过$(element).css('fill')获取到的颜色值默认是RGB格式(比如rgb(75, 189, 222)),和你用来匹配的十六进制色值#4bbdde格式不一致,判断条件永远为假。

解决方法

  1. 绑定Google Charts的ready事件,等图表完全渲染完成后再执行DOM操作
  2. 直接获取<rect>元素的fill属性值做匹配,不需要通过css方法获取,可避免格式转换的额外处理

可运行完整代码

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['timeline']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var container = document.getElementById('timeline');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();

        dataTable.addColumn({ type: 'string', id: 'President' });
        dataTable.addColumn({  type: 'string', id: 'Bar'});
        dataTable.addColumn({  type: 'string', role: 'style'});
        dataTable.addColumn({ type: 'date', id: 'Start' });
        dataTable.addColumn({ type: 'date', id: 'End' });
        dataTable.addRows([
          [ 'Washington','Washington','#4bbdde', new Date(1789, 3, 30), new Date(1797, 2, 4) ],
        ]);
        // 绑定ready事件,确保图表渲染完成后再操作DOM
        google.visualization.events.addListener(chart, 'ready', function () {
          var matchColor = '#4bbdde';
          $('rect').filter(function() {
            // 直接获取fill属性值匹配,无需处理格式转换
            return $(this).attr('fill') === matchColor;
          }).css('fill', '#000000');
        });
        chart.draw(dataTable);
      }
    </script>
  </head>
  <body>
    <div id="timeline" style="height: 180px;"></div>
  </body>
</html>

内容的提问来源于stack exchange,提问作者bart cubrich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 23:27:04