Javascript Chart.js:更改工具提示模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30500601/
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:17:04  来源:igfitidea点击:

Chart.js: changing tooltip template

javascriptchart.js

提问by cincplug

I need to change Chart.js tooltip template, so that only value part is displayed in bold. There is tooltipTemplate option, which should do exactly this. Default value of this option is:

我需要更改 Chart.js 工具提示模板,以便仅以粗体显示值部分。有 tooltipTemplate 选项,它应该完全做到这一点。此选项的默认值为:

tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>%"

I tried editing it like this:

我试着像这样编辑它:

tooltipTemplate: "<%if (label){%><%=label%>: <%}%><strong><%= value %></strong>%"

But it displays strongtags on screen as part of text, instead of rendering bold text. I tried moving them around <%and %>, but it still doesn't work. Any ideas?

但它将strong标签作为文本的一部分显示在屏幕上,而不是呈现粗体文本。我试着移动它们<%%>,但它仍然不起作用。有任何想法吗?

回答by potatopeelings

The template does not recognize HTML. You have to use the customTooltips option. Below is an example adapted (but not optimized) from https://github.com/nnnick/Chart.js/blob/master/samples/line-customTooltips.html

该模板无法识别 HTML。您必须使用 customTooltips 选项。以下是从https://github.com/nnnick/Chart.js/blob/master/samples/line-customTooltips.html改编(但未优化)的示例

HTML

HTML

<canvas id="myChart" width="400" height="200"></canvas>
<div id="chartjs-tooltip"></div>

CSS

CSS

#chartjs-tooltip {
     opacity: 0;
     position: absolute;
     background: rgba(0, 0, 0, .7);
     color: white;
     padding: 3px;
     border-radius: 3px;
     -webkit-transition: all .1s ease;
     transition: all .1s ease;
     pointer-events: none;
     -webkit-transform: translate(-50%, 0);
     transform: translate(-50%, 0);
 }

JS

JS

var ctx = $("#myChart").get(0).getContext("2d");

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.2)",
        strokeColor: "rgba(220,220,220,1)",
        pointColor: "rgba(220,220,220,1)",
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 59, 80, 81, 56, 55, 40]
    }]
};

var myLineChart = new Chart(ctx).Line(data, {
    customTooltips: function (tooltip) {
        var tooltipEl = $('#chartjs-tooltip');

        if (!tooltip) {
            tooltipEl.css({
                opacity: 0
            });
            return;
        }

        tooltipEl.removeClass('above below');
        tooltipEl.addClass(tooltip.yAlign);

        // split out the label and value and make your own tooltip here
        var parts = tooltip.text.split(":");
        var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
        tooltipEl.html(innerHtml);

        tooltipEl.css({
            opacity: 1,
            left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
            top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
            fontFamily: tooltip.fontFamily,
            fontSize: tooltip.fontSize,
            fontStyle: tooltip.fontStyle,
        });
    }
});

Fiddle - http://jsfiddle.net/6rxdo0c0/1/

小提琴 - http://jsfiddle.net/6rxdo0c0/1/

回答by olidem

I have an up-to-date answer using jquery and bootstrap 4 tooltips that creates the tooltip divs dynamically. Assume your html is

我有一个使用 jquery 和 bootstrap 4 工具提示动态创建工具提示 div 的最新答案。假设你的 html 是

<canvas id="myPieChart" width="100" height="55"></canvas>

Then use this script:

然后使用这个脚本:

<script>  
    $(document).ready(function() {   

        let canvas = $("#donutChart")[0];
        let ctx = canvas.getContext("2d");

        let donutChart = new Chart(ctx, {
            type: 'doughnut',
            data: data,
            options: {

                tooltips: {

                    callbacks: {
                        title: function(){
                            return null;
                        },
                        label: function(tooltipItem, data) {
                            var multiline = ['First Line', 'second line'];
                            return multiline;
                        },

                    },
                    enabled: false, // the builtin tooltips cannot extend beyond the canvas

                    custom: function(tooltip) {

                        var tooltipEl = $('#chartjs-tooltip');

                        if(tooltipEl.length == 0) { // if not exists, create it
                            tooltipEl = $('<div class="tooltip fade" id="chartjs-tooltip"></div>').appendTo('body');
                        }

                        if ( !tooltip.body ) { // Hide if no tooltip
                            tooltipEl.remove();
                            return;
                        }


                        tooltipEl.removeClass('bs-tooltip-top bs-tooltip-bottom');
                        tooltipEl.addClass( 'bs-tooltip-' + (tooltip.yAlign == "bottom" ? "top" : "bottom") ); // different naming in bootstrap

                        var innerHtml = '<div class="arrow" style="left: '+tooltip.caretX+'px;"></div>'
                            + '<div class="tooltip-inner" style="max-width: none;">' + tooltip.body[0].join('<br>')
                            + '</div>';
                        tooltipEl.html( innerHtml );
                        tooltipEl.css( {
                            opacity: 1,
                            left: $("#donutChart").offset().left + tooltip.x + 'px',
                            top: $("#donutChart").offset().top + tooltip.y + 'px'
                        } );

                    },
                },
                hover: { 
                    mode: null,
                },
            }
        });
    });
</script>