我正在使用chartjs 2.8
,并为此创建了一些自定义html工具提示,现在我需要使tooltip
具有交互性(又名-悬停,可点击等)
问题在于,当我将鼠标悬停在要在工具提示中看到的数据点上时,chartjs仅显示工具提示,一旦我将鼠标悬停在工具提示中时它就会消失。
我曾尝试检查一下chartjs文档中的某些选项解决方案,但找不到任何有用的方法。
我一直在考虑与customTooltip function
一起玩,因此tooltipModel.opacity===0
只会消失一次,并且鼠标不在工具提示中,但是我在这里遇到了一些困难
this.tooltip = $('<div/>').addClass('chartjs-tooltip')[0];
document.body.appendChild(this.tooltip);
return new Chart($chart, {
type: 'line',
data: {
labels: labels,
datasets: datasets,
cubicInterpolationMode: 'monotone'
},
options: Object.assign({}, options, {
tooltips: {
// Disable the on-canvas tooltip
enabled: false,
custom: (tooltipModel) => {
// Hide if no tooltips
if (tooltipModel.opacity === 0) {
$(this.tooltip).empty().removeClass('visible');
return;
} else {
$(this.tooltip).addClass('visible');
}
// Set caret Position
this.tooltip.classList.remove('above', 'below', 'no-transform');
if (tooltipModel.yAlign) {
this.tooltip.classList.add(tooltipModel.yAlign);
} else {
this.tooltip.classList.add('no-transform');
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Set Text
if ( empty_datapoint ) {
if (tooltipModel.body) {
this.tooltip.innerHTML = '<table></table>';
let titleLines = tooltipModel.title || [];
let bodyLines = tooltipModel.body.map(getBody);
let innerHtml = '<thead>';
titleLines.forEach(function(title) {
innerHtml += '<tr><th>' + title + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach(function(body, i) {
let colors = tooltipModel.labelColors[i];
let style = 'background:' + colors.backgroundColor + ';';
let span = '<span class="color-box" style="' + style + '"></span>';
innerHtml += '<tr><td>' + span + body + '</td></tr>';
});
innerHtml += '</tbody>';
let tableRoot = this.tooltip.querySelector('table');
tableRoot.innerHTML = innerHtml;
this.tooltip.addStyles({
backgroundColor: 'rgba(0,0,0,0.8)',
borderRadius: '6px',
color: '#fff',
fontFamily: tooltipModel._bodyFontFamily,
fontSize: tooltipModel.bodyFontSize + 'px',
fontStyle: tooltipModel._bodyFontStyle,
});
}
} else {
let $tooltip = this.customTooltip(tooltipModel.dataPoints);
$('.chartjs-tooltip').html($tooltip);
tooltipModel.caretX += -150;
}
// `this` will be the overall tooltip
let position = this.chart.$el.canvas.getBoundingClientRect();
// Display, position, and set styles for font
this.tooltip.addStyles({
position: 'absolute',
left: position.left + window.pageXOffset + tooltipModel.caretX + 'px',
top: position.top + window.pageYOffset + tooltipModel.caretY + 'px',
padding: tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px',
zIndex: 9999999999,
// pointerEvents: 'none'; // pretty sure we'll want pointer event in the future
});
}
}
}),
});