我目前正在摆弄一些图表,我希望当你将鼠标悬停在某些数据点上时会出现一串文字。
例如,目前我的数据集如下所示:
var data = {
labels: ["January", "February:", "March", "April", "May", "June", "July"],
datasets: [{
label: "My first dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}]
};
我想举例说,将鼠标悬停在二月:59点上并显示"二月:59 - 一些独特的文字"
谢谢
答案 0 :(得分:0)
首先在html中添加
<canvas id="myChart" width="400" height="200"></canvas>
<div id="chartjs-tooltip"></div>
:JS
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}]
};
var myLineChart = new Chart(ctx).Line(data, {
customTooltips: function (tooltip) {
var tooltipEl = $('#chartjs-tooltip');
if (!tooltip) {
tooltipEl.css({
opacity: 0
});
return;
}
tooltipEl.removeClass('above below');
tooltipEl.addClass(tooltip.yAlign);
// split out the label and value and make your own tooltip here
var parts = tooltip.text.split(":");
var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
tooltipEl.html(innerHtml);
tooltipEl.css({
opacity: 1,
left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
fontFamily: tooltip.fontFamily,
fontSize: tooltip.fontSize,
fontStyle: tooltip.fontStyle,
});
}
});
和一些造型的东西
:CSS
#chartjs-tooltip {
opacity: 0;
position: absolute;
background: rgba(0, 0, 0, .7);
color: white;
padding: 3px;
border-radius: 3px;
-webkit-transition: all .1s ease;
transition: all .1s ease;
pointer-events: none;
-webkit-transform: translate(-50%, 0);
transform: translate(-50%, 0);
}
答案 1 :(得分:0)
(注意 Chart.js 已经自动添加了工具提示文本;上面的问题有点不清楚。问题是关于如何向工具提示添加自定义文本,而不仅仅是默认值它选择 - 给定点的 x 和 y 值。)
使用 callbacks
中的 options.tooltips
字段。请注意,工具提示的正文称为“标签”。
tooltips: {
intersect: false, // makes it easier to select tooltips on mobile
callbacks: {
title: (toolTipItem, data) => {
let title = toolTipItem[0].x; // uses the x value of this point as the title
return title;
},
label: (toolTipItem, data) => {
let labels = data[toolTipItem.index!].labelText; // assumes your data has a `labelText` field.
return labels;
},
},
},
请注意,某些字段(例如 title
)在其回调中传递了一个 toolTipItem
对象数组;其他的,比如 label
,被传递一个单一的对象。因此,必须对每个对象的 toolTipItem
对象的属性进行不同的访问。
toolTipItem
对象上访问的属性 - https://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-item-interface