How to make tool tip contents display on multiple lines

陌路散爱 提交于 2019-12-24 08:37:53

问题


I'm using Chart.js and I can't seem to insert a line break into the tool tip text. I've tried \n, but that doesn't seem to work for me. How else should I go about doing this?


回答1:


Chart.js uses canvas fillText for the tooltips in it's default tooltip function. fillText unfortunately doesn't support word wrapping.

So you'll have to write your own custom tooltip function. There again, the labels are also used for the x axis. The easiest way would be to use \b (it's just ignored in your axis fillText) and swap it out in your custom tooltip function.


Preview


Code

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

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

        // split out the label and value and make your own tooltip here
        var parts = tooltip.text.split(":");
        var re = new RegExp('\b', 'g');
        var innerHtml = '<span>' + parts[0].trim().replace(re, '<br/>') + '</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,
        });
    }
});

with the following markup added (your tooltip wrapper)

<div id="chartjs-tooltip"></div>

and the following CSS (for positioning your tooltip)

 #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%, -120%);
     transform: translate(-50%, -120%);
 }

and your labels would look like

labels: ["Jan\bua\bry", "February", "Mar\bch", "April", "May", "June", "July"],

with \b standing for breaks. Note that you \n, \r, \t, \f... won't work if you don't want spaces in your x axis labels. If you actually want there to be spaces just use \n or something and change the RegEx accordingly

Fiddle - http://jsfiddle.net/5h1r71g8/



来源:https://stackoverflow.com/questions/31094100/how-to-make-tool-tip-contents-display-on-multiple-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!