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

Google Charts自定义Tooltip无法正常显示问题求助

Google Charts 自定义Tooltip不显示问题修复

问题原因分析

你的代码存在两个关键问题导致自定义Tooltip无法生效:

  1. 语法错误:createCustomHTMLContent函数中出现无效的+n,导致JavaScript报错,函数无法返回正确的HTML内容。
  2. HTML转义错误:返回的内容使用了</>这类HTML转义字符,Google Charts会将其当作纯文本渲染,而非解析为HTML标签。

修复后的代码

JavaScript部分

google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);

function createCustomHTMLContent(month, year, value) {
  // 动态生成对应数据点的Tooltip内容,可按需自定义样式
  return `<div>${month} ${year}: <strong>${value} kWh</strong></div>`;
}

function drawVisualization() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');
  // 定义支持HTML的Tooltip角色列
  data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
  data.addColumn('number', '2023');
  data.addColumn('number', '2024');

  data.addRows([
    ['Jan', createCustomHTMLContent('Jan', 2023, 165), 165, 614.6],
    ['Feb', createCustomHTMLContent('Feb', 2023, 135), 135, 682],
    ['Mar', createCustomHTMLContent('Mar', 2023, 157), 157, 623],
    ['Apr', createCustomHTMLContent('Apr', 2023, 139), 139, 609.4],
    ['May', createCustomHTMLContent('May', 2023, 136), 136, 569.6],
    ['Jun', createCustomHTMLContent('Jun', 2023, 165), 165, 614.6],
    ['Aug', createCustomHTMLContent('Aug', 2023, 135), 135, 682],
    ['Sep', createCustomHTMLContent('Sep', 2023, 157), 157, 623],
    ['Oct', createCustomHTMLContent('Oct', 2023, 139), 139, 609.4],
    ['Nov', createCustomHTMLContent('Nov', 2023, 136), 136, 569.6],
    ['Dec', createCustomHTMLContent('Dec', 2023, 136), 136, 569.6],
  ]);
  
  var options = {
    vAxis: {
      title: 'Usage in kWh',
      titleTextStyle : {
        fontName : "Oswald",
        italic : false,
      }
    },
    hAxis: {
      title: 'Month',
      titleTextStyle : {
        fontName : "Oswald",
        italic : false,
      }
    },
    seriesType: 'bars',
    series: {
      0: { color: '#1f6099' },
      1: {type: 'line', pointsVisible: true, color: '#2AB673'}
    },
    legend: { position: 'bottom', alignment: 'center' },
    tooltip: { isHtml: true }, // 必须开启HTML解析模式
  };

  var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
  chart.draw(data, options);
}

HTML部分

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

关键修改说明

  • 移除createCustomHTMLContent函数中的无效代码+n,使用JavaScript模板字符串直接编写HTML内容,避免转义字符导致的解析问题。
  • 优化Tooltip生成逻辑,动态传入数据点参数,让Tooltip内容与对应数据匹配。
  • 确保Tooltip角色列的p: {'html': true}配置和全局选项的tooltip.isHtml: true同时生效,保证Google Charts正确解析HTML格式的Tooltip。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:05:25