我正在尝试在使用Chartjs制作的图表中实现hover
回调。这是我感到困惑的以下部分:
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
// Am I supposed to put onHover callback inside of hover property of options?
//hover: {
// onHover: (e, elements): void => {}
//}
// OR
// Am I supposed to put onHover callback just as a property of options?
// onHover: (e, elements): void => {}
}
});
棘手的部分是,我尝试了两种方法,并且两种方法都有效。我一直在研究他们的文档,但似乎没有正确的方法。根据他们的文档,onHover
:Called when any of the events fire. Called in the context of the chart and passed the event and an array of active elements (bars, points, etc).
是否仅当触发hover
事件时才调用它?任何见识将不胜感激!
您应该在悬停选项内实现onHover回调,以便您可以指定选项。对于所有其他事件,事件悬停很容易触发,因为它们具有悬停功能,即事件单击,悬停然后单击。
var chart = new Chart(document.getElementById('chart').getContext('2d'), {
options: {
hover: {
mode: 'nearest',
intersect: false,
onHover: function (e, element) {
if (item.length) {
const data = item[0]._chart.config.data.datasets[0].data[item[0]._index];
console.log(item, data);
}
}
}
}
});