如何修改chartjs工具提示以添加自定义属性

时间:2015-12-07 16:30:01

标签: chart.js

我如何编辑工具提示模板,我可以从我的json文件中添加自定义属性?在示例下方:

ChartJS Example

在x轴上是带有第一个字母的月份,但在工具提示中我想显示当月的前三个字母 - 我该怎么做?

编辑:我的JSON文件:

{"modules":[{
"name":"Chart 1",
"link":"www.google.com",
"type":"Bar",
"series":"SeriesA",
"data":[[20,40,50,40,20,20,20,20,20,20,20,20]],
"labels":["M","J","J","A","S","O","N","D","J","F","M","A","M"],
"colors":[{
    "fillColor":"blue"
    }],
"options":{
    "scaleShowGridLines":false
    }

    }]}

2 个答案:

答案 0 :(得分:1)

工具提示与比例的不同标签

只需使用tooltipTemplate选项

即可

预览

enter image description here

<强>脚本

function Label(short, long) {
  this.short = short;
  this.long = long
}
Label.prototype.toString = function() {
  return this.short;
}

var data = {
    labels: [ 
      new Label("J", "JAN"), 
      new Label("F", "FEB"), 
      new Label("M", "MAR"),
      new Label("A", "APR"),
      new Label("M", "MAY"),
      new Label("J", "JUN"),
      new Label("J", "JUL")
    ],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(220,220,220,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }
    ]
};

// create chart
var ctx = document.getElementById("chart").getContext('2d');
new Chart(ctx).Bar(data, {
  tooltipTemplate: "<%if (label){%><%=label.long%>: <%}%><%= value %>",
});

小提琴 - https://jsfiddle.net/7z1s1feg/

答案 1 :(得分:0)

This part文档解释了如何扩展工具提示元素。

var myPieChart = new Chart(ctx).Pie(data, {
    customTooltips: function(tooltip) {

    };
});

另外,this example向您展示如何修改此函数中工具提示的HTML。来自GitHub的例子:

var innerHtml = '';
    for (var i = tooltip.labels.length - 1; i >= 0; i--) {
        innerHtml += [
            '<div class="chartjs-tooltip-section">',
            '   <span class="chartjs-tooltip-key" style="background-color:' + tooltip.legendColors[i].fill + '"></span>',
            '   <span class="chartjs-tooltip-value">' + tooltip.labels[i] + '</span>',
            '</div>'
        ].join('');
    }
    tooltipEl.html(innerHtml);

使用这些元素,您可以根据需要自定义工具提示。