Chart JS在工具提示中显示HTML [英] Chart JS Show HTML in Tooltip

查看:111
本文介绍了Chart JS在工具提示中显示HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在与Chart JS的文档作斗争,试图找出当您将鼠标悬停在特定点上时如何修改折线图工具提示的内容。



基本上,我想在单个点悬停时在所有相同的垂直轴上显示值。我尝试过这样的事情:

 工具提示:{
回调:{
label:function( tooltipItem,data){
console.log(data);
var html =;
for(data.datasets中的var数据集){
html + =< label> + data.datasets [dataset] .label +:+ data.datasets [dataset] .data [tooltipItem.index] +%< / label>< br />;
}
返回html;
}
},
},

这适用于每个数据集的循环程度和附加< label>示例:每个数据集的0%< br />< / label> 但是当我返回时HTML,工具提示字面上显示字符串:

 < label>示例1:1%< / label>< br / >< label>示例2:5%< / label>< br /> ... 

而不是呈现正确的HTML:

 示例1:1%
示例2:5%
...

现在,我知道Chart JS 1.0版有 tooltipTemplate 选项,但我似乎无法弄清楚是否有以任何方式在 tooltips.callbacks.label 选项中返回HTML。有关于如何进行自定义工具提示的文档,如果我无法解决这个问题,我将最终使用它,但任何帮助都将不胜感激。

解决方案

从v2.4开始,遗憾的是回调当前不允许使用HTML。你需要编写一个自定义工具提示函数。



例子可以在chart-js的samples文件夹中找到(虽然有些比我发现的更好)。 / p>

https ://github.com/chartjs/Chart.js/tree/v2.4.0/samples/tooltips



尝试运行示例以获得感觉选项和修改如何影响工具提示功能。



例如在自定义函数的折线图示例中:

  Chart.defaults.global.pointHitDetectionRadius = 1; 
var customTooltips = function(tooltip){
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
if(!tooltipEl){
tooltipEl = document.createElement('div');
tooltipEl.id ='chartjs-tooltip';
tooltipEl.innerHTML =< table>< / table>
document.body.appendChild(tooltipEl);
}
//隐藏如果没有工具提示
if(tooltip.opacity === 0){
tooltipEl.style.opacity = 0;
返回;
}
//设置插入位置
tooltipEl.classList.remove('above','below','no-transform');
if(tooltip.yAlign){
tooltipEl.classList.add(tooltip.yAlign);
} else {
tooltipEl.classList.add('no-transform');
}
函数getBody(bodyItem){
return bodyItem.lines;
}
//设置Text
if(tooltip.body){
var titleLines = tooltip.title || [];
var bodyLines = tooltip.body.map(getBody);
// PUT CUSTOM HTML TOOLTIP CONTENT(innerHTML)
var innerHtml ='< thead>';
titleLines.forEach(function(title){
innerHtml + ='< tr>< th>'+ title +'< / th>< / tr>';
});
innerHtml + ='< / thead>< tbody>';
bodyLines.forEach(function(body,i){
var colors = tooltip.labelColors [i];
var style ='background:'+ colors.backgroundColor;
style + ='; border-color:'+ colors.borderColor;
style + ='; border-width:2px';
var span ='< span class =chartjs-tooltip-key style ='+ style +'>< / span>';
innerHtml + ='< tr>< td>'+ span + body +'< / td>< / tr> ;';
});
innerHtml + ='< / tbody>';
var tableRoot = tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
var position = this._chart.canvas.getBoundingClientRect();
//字体的显示,位置和设置样式
tooltipEl.style.opacity = 1;
tooltipEl.style.left = position.left + tooltip.caretX +'px';
tooltipEl.style.top = position.top + tooltip.caretY +'px';
tooltipEl.style.fontFamily = tooltip._fontFamily;
tooltipEl.style.fontSize = tooltip.fontSize;
tooltipEl.style.fontStyle = tooltip._fontStyle;
tooltipEl.style.padding = tooltip.yPadding +'px'+ tooltip.xPadding +'px';
};

然后将其设置为图表选项中的自定义工具提示功能:

  window.myLine = new Chart(chartEl,{
type:'line',
data:lineChartData,
选项:{
title:{
display:true,
text:'Chart.js折线图 - 自定义工具提示'
},
工具提示:{
启用:false,
模式:'index',
position:'nearest',
//在此处设置自定义函数的名称
custom:customTooltips
}
}
});

编辑:道歉,我只阅读你问题的标题,而不是完整的问题。通过将交互模式更改为选项中的索引,您可以更简单地在工具提示中使用HTML(除非是出于其他原因需要)。有一个样本可以显示它是如何工作的。


I've been fighting with Chart JS's documentation trying to figure out how to modify the content of a line chart's tool tip when you hover over a specific point.

Basically, I want to display the values on all the same vertical axis whenever a single point is hovered over. I've tried something like this:

tooltips: {
    callbacks: {
        label: function(tooltipItem, data){
            console.log(data);
            var html = "";
            for(var dataset in data.datasets){
                html += "<label>" + data.datasets[dataset].label + ": " + data.datasets[dataset].data[tooltipItem.index] + "%</label><br/>";
            }
            return html;
        }
    },
},

This works to the degree of looping over each data set and appending <label>Example: 0%<br/></label> for each dataset, but when I return that HTML, the tooltip literally displays the string:

<label>Example1: 1%</label><br/><label>Example2: 5%</label><br/> ...

Instead of rendering the correct HTML:

Example1: 1%
Example2: 5%
...

Now, I know that Chart JS version 1.0 has the tooltipTemplate option, but I can't seem to figure out if there is any way to return HTML in the tooltips.callbacks.label option. There's documentation for how to do custom tooltips, which I will end up using if I can't figure this out, but any help would be appreciated.

解决方案

As of v2.4, the callbacks unfortunately don't allow for HTML currently. You'll need to write a custom tooltip function.

Examples can be found in the samples folder for chart-js (although some are better than others I found).

https://github.com/chartjs/Chart.js/tree/v2.4.0/samples/tooltips

Try running the samples to get a feel for how the options and modifications affect the tooltip function.

For example in the line chart example of a custom function:

Chart.defaults.global.pointHitDetectionRadius = 1;
var customTooltips = function(tooltip) {
    // Tooltip Element
    var tooltipEl = document.getElementById('chartjs-tooltip');
    if (!tooltipEl) {
        tooltipEl = document.createElement('div');
        tooltipEl.id = 'chartjs-tooltip';
        tooltipEl.innerHTML = "<table></table>"
        document.body.appendChild(tooltipEl);
    }
    // Hide if no tooltip
    if (tooltip.opacity === 0) {
        tooltipEl.style.opacity = 0;
        return;
    }
    // Set caret Position
    tooltipEl.classList.remove('above', 'below', 'no-transform');
    if (tooltip.yAlign) {
        tooltipEl.classList.add(tooltip.yAlign);
    } else {
        tooltipEl.classList.add('no-transform');
    }
    function getBody(bodyItem) {
        return bodyItem.lines;
    }
    // Set Text
    if (tooltip.body) {
        var titleLines = tooltip.title || [];
        var bodyLines = tooltip.body.map(getBody);
        //PUT CUSTOM HTML TOOLTIP CONTENT HERE (innerHTML)
        var innerHtml = '<thead>';
        titleLines.forEach(function(title) {
            innerHtml += '<tr><th>' + title + '</th></tr>';
        });
        innerHtml += '</thead><tbody>';
        bodyLines.forEach(function(body, i) {
            var colors = tooltip.labelColors[i];
            var style = 'background:' + colors.backgroundColor;
            style += '; border-color:' + colors.borderColor;
            style += '; border-width: 2px'; 
            var span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
            innerHtml += '<tr><td>' + span + body + '</td></tr>';
        });
        innerHtml += '</tbody>';
        var tableRoot = tooltipEl.querySelector('table');
        tableRoot.innerHTML = innerHtml;
    }
    var position = this._chart.canvas.getBoundingClientRect();
    // Display, position, and set styles for font
    tooltipEl.style.opacity = 1;
    tooltipEl.style.left = position.left + tooltip.caretX + 'px';
    tooltipEl.style.top = position.top + tooltip.caretY + 'px';
    tooltipEl.style.fontFamily = tooltip._fontFamily;
    tooltipEl.style.fontSize = tooltip.fontSize;
    tooltipEl.style.fontStyle = tooltip._fontStyle;
    tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};

Then set this as the custom tooltip function in the options for the chart:

window.myLine = new Chart(chartEl, {
    type: 'line',
    data: lineChartData,
    options: {
        title:{
            display:true,
            text:'Chart.js Line Chart - Custom Tooltips'
        },
        tooltips: {
            enabled: false,
            mode: 'index',
            position: 'nearest',
            //Set the name of the custom function here
            custom: customTooltips
        }
    }
});

EDIT: Apologies, I only read the title of your question, not the full question. What you ask can be done more simply and without HTML in the tooltips (unless it's required for another reason) by changing the interaction mode to index in the options. There's a sample available to show how this works.

这篇关于Chart JS在工具提示中显示HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆