以编程方式打开和关闭 Chart.js 工具提示

2022-01-22 00:00:00 charts javascript chart.js

Chart.js 2.2.1

知道如何触发当我将鼠标悬停在数据点上时运行的代码以及当我移开鼠标时运行的代码吗?我需要以编程方式显示和隐藏图表的工具提示.

Any idea how to trigger the code that runs when I hover over a datapoint, and that runs when I move the mouse off? I need to programmatically show and hide a chart's tooltip.

openTip(oChart, datasetIndex, pointIndex){
   // how to open a specific tooltip?
}
closeTip(oChart, datasetIndex, pointIndex){
   // how to close the same tooltip?
}

如果可以的话,我会展示示例代码,但我什至不知道从哪里开始.图表方法文档没有帮助.

I would show sample code if I could, but I don't even know where to start. The chart method docs haven't helped.

JSFiddle

推荐答案

下面的代码将处理一个或多个工具提示.

The code below will handle one or more tooltips.

function openTip(oChart,datasetIndex,pointIndex){
   if(window.oChart.tooltip._active == undefined)
      window.oChart.tooltip._active = []
   var activeElements = window.oChart.tooltip._active;
   var requestedElem = window.oChart.getDatasetMeta(datasetIndex).data[pointIndex];
   for(var i = 0; i < activeElements.length; i++) {
       if(requestedElem._index == activeElements[i]._index)  
          return;
   }
   activeElements.push(requestedElem);
   //window.oChart.tooltip._view.body = window.oChart.getDatasetMeta(datasetIndex).data;
   window.oChart.tooltip._active = activeElements;
   window.oChart.tooltip.update(true);
   window.oChart.draw();
}

function closeTip(oChart,datasetIndex,pointIndex){
   var activeElements = window.oChart.tooltip._active;
   if(activeElements == undefined || activeElements.length == 0)
     return;
   var requestedElem = window.oChart.getDatasetMeta(datasetIndex).data[pointIndex];
   for(var i = 0; i < activeElements.length; i++) {
       if(requestedElem._index == activeElements[i]._index)  {
          activeElements.splice(i, 1);
          break;
       }
   }
   window.oChart.tooltip._active = activeElements;
   window.oChart.tooltip.update(true);
   window.oChart.draw();
}

@BeetleJuice 提供的完整解决方案 - https://jsfiddle.net/ucvvvnm4/5/

Complete solution provided by @BeetleJuice - https://jsfiddle.net/ucvvvnm4/5/

相关文章