Javascript 当鼠标悬停统计时,Chartjs 显示标签和单位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30334965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:00:37  来源:igfitidea点击:

Chartjs display label & units when mouse is hover stats

javascriptjqueryruby-on-railslabelchart.js

提问by Stéphane

Is it possible to have the label & units when my mouse pointer is hover the chart ? For now there is only the number.

当我的鼠标指针悬停在图表上时,是否可以使用标签和单位?目前只有数字。

For the example bellow I would like to show :

对于下面的示例,我想展示:

  • 58% Label1
  • 0% Label2
  • 0% Label3
  • 0% Label4
  • 0% Label5
  • 58% 标签1
  • 0% 标签 2
  • 0% 标签 3
  • 0% 标签4
  • 0% 标签5

enter image description here

在此处输入图片说明

My options looks like this :

我的选择是这样的:

var options = {
      //Boolean - Show a backdrop to the scale label
      scaleShowLabelBackdrop : true,
      //Boolean - Whether to show labels on the scale
      scaleShowLabels : true,
      // Boolean - Whether the scale should begin at zero
      scaleBeginAtZero : true,
      scaleLabel : "<%%= Number(value) + ' %'%>",
      legendTemplate: "<ul class=\"<%%=name.toLowerCase()%>-legend\"><%% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%%=datasets[i].strokeColor%>\"></span><%%if(datasets[i].label){%><%%=datasets[i].label%> <strong><%%=datasets[i].value%></strong><%%}%></li><%%}%></ul>",
      tooltipTemplate: "<%%= value %> Label"
    }

With scaleLabel option I have the % shown on the Y-axis but not on the hover pop-up...

使用 scaleLabel 选项,我的 % 显示在 Y 轴上,但不在悬停弹出窗口上...

回答by Stéphane

I found the solution on the ChartJS repository on Github.

在 Github 的 ChartJS 存储库中找到了解决方案。

The solution is to use the option multiTooltipTemplateif your graph has multiple data. Otherwise, you should use tooltipTemplate

multiTooltipTemplate如果您的图表有多个数据,则解决方案是使用该选项。否则,你应该使用tooltipTemplate

multiTooltipTemplate: "<%=datasetLabel%> : <%= value %>"  // Regular use
// or
multiTooltipTemplate: "<%%=datasetLabel%> : <%%= value %>"  // Ruby on Rails use

Will give you :

会给你 :

  • Dataset_label : value
  • 数据集标签:值

回答by rohit kumbhar

Try this one, it will work. You just need to check what's the data coming in the label function.

试试这个,它会起作用。您只需要检查标签函数中的数据是什么。

options: {
  tooltips: {
    callbacks: {
      title: function() {
        return "";
      },
      label: function(item, data) {
        var datasetLabel = data.datasets[item.datasetIndex].label || "";
        var dataPoint = item.yLabel;
        return datasetLabel + ": " + dataPoint + "min";
      }
    }
  }
}