遗憾的是,从 v2.4 开始,回调目前不允许 HTML。您需要编写一个自定义工具提示函数。
可以在 chart-js 的示例文件夹中找到示例(尽管有些比我找到的其他更好)。
https://github.com/chartjs/Chart.js/tree/v2.4.0/samples/tooltips
尝试运行示例以了解选项和修改如何影响工具提示功能。
以自定义函数的折线图示例为例:
Chart.defaults.global.pointHitDetectionRadius = 1;
var customTooltips = function(tooltip) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
if (!tooltipEl) {
tooltipEl = document.createElement('div');
tooltipEl.id = 'chartjs-tooltip';
tooltipEl.innerHTML = "<table></table>"
document.body.appendChild(tooltipEl);
}
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if (tooltip.body) {
var titleLines = tooltip.title || [];
var bodyLines = tooltip.body.map(getBody);
//PUT CUSTOM HTML TOOLTIP CONTENT HERE (innerHTML)
var innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
var colors = tooltip.labelColors[i];
var style = 'background:' + colors.backgroundColor;
style += '; border-color:' + colors.borderColor;
style += '; border-width: 2px';
var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
var position = this._chart.canvas.getBoundingClientRect();
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.left = position.left + tooltip.caretX + 'px';
tooltipEl.style.top = position.top + tooltip.caretY + 'px';
tooltipEl.style.fontFamily = tooltip._fontFamily;
tooltipEl.style.fontSize = tooltip.fontSize;
tooltipEl.style.fontStyle = tooltip._fontStyle;
tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};
然后将此设置为图表选项中的自定义工具提示功能:
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title:{
display:true,
text:'Chart.js Line Chart - Custom Tooltips'
},
tooltips: {
enabled: false,
mode: 'index',
position: 'nearest',
//Set the name of the custom function here
custom: customTooltips
}
}
});
编辑:抱歉,我只阅读了您的问题的标题,而不是完整的问题。通过将交互模式更改为选项中的索引,您可以更简单地完成您的要求,并且工具提示中没有 HTML(除非出于其他原因需要)。有一个示例可以展示它是如何工作的。