简体   繁体   English

chart.js之工具提示值在两行显示

[英]Chart.js tooltip values display in two lines

I am using chart.js.我使用chart.js之。 I want to show on hover two values in tooltip.我要显示在工具提示悬停两个值。 Both of them in new line, but i really dont know how.他们都在新的生产线,但我真的不知道怎么办。 This example still return string in one line.这个例子仍然在一行返回的字符串。 I tried es6 syntax with `` but without any success.我试图ES6语法与``但没有成功。 Is there any way to archive that without using custom html?有没有什么办法来归档,而不使用自定义HTML?

tooltips: {
    callbacks: {
        label: function(tooltipItem, data) {
            var someValue = "dasdasd";
            var someValue2 = "dasdasda2";
            return someValue + "/n" + someValue2;
        },
    }
},

You cannot use new-line ( \\n ) character or ES6 syntax for that matter (as canvas/chart.js doesn't support it) .您不能为此使用换行符( \\n )字符或 ES6 语法(因为 canvas/chart.js 不支持它)

Instead, you should use the afterLabel callback function of tooltips, which returns a text to render after an individual label.相反,您应该使用工具提示的afterLabel回调函数,该函数返回要在单个标签之后呈现的文本。

Example例子

 var chart = new Chart(ctx, { type: 'line', data: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'], datasets: [{ label: 'LINE', data: [3, 1, 4, 2, 5], backgroundColor: 'rgba(0, 119, 290, 0.2)', borderColor: 'rgba(0, 119, 290, 0.6)' }] }, options: { tooltips: { callbacks: { label: function(tooltipItem, data) { var someValue = "Hello"; return someValue; }, afterLabel: function(tooltipItem, data) { var someValue2 = "Mindfuc"; return someValue2; } } } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script> <canvas id="ctx"></canvas>

there are also other options how to split two lines in chart js tooltips:也有其他的选择如何分割在图表JS提示两行:

  1. By default, values are separated if provided in an array ( source ), so in your case you could try:默认情况下,如果在一个阵列(提供的值是分开的来源),所以你的情况,你可以尝试:

     return [someValue, someValue2];
  2. Or alternatively, you can use split ( source ): ,或者也可以使用split来源):

     return (someValue + "/n" + someValue2).split('\\n');

Both options should provide same result.这两种方法都应该提供同样的结果。

This worked for me.这对我有用。 Just simply return an array of strings as labels in tooltips callbacks.只需简单地返回一个字符串数组作为工具提示回调中的标签。

 tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        let label = "Line 1";
        let label2 = "Line 2";
        return [label, label2];
      }
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM