Programmatically open and close Chart.js tooltip

后端 未结 2 885
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 10:41

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 programmaticall

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-09 11:17

    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();
    }
    

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

提交回复
热议问题