如何使工具提示内容显示在多行上 [英] How to make tool tip contents display on multiple lines

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

问题描述

我正在使用Chart.js,但似乎无法在工具提示文本中插入换行符。我尝试过\n,但这似乎对我不起作用。我该怎么办?

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?

推荐答案

Chart.js在其默认工具提示功能中使用canvas fillText作为工具提示。不幸的是,fillText不支持自动换行。

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

因此,您必须编写自己的自定义工具提示功能。同样,标签也用于x轴。最简单的方法是使用\b(在轴上的fillText中被忽略)并在自定义工具提示函数中将其换出。

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.

预览

< a href = https://i.stack.imgur.com/yvftR.png rel = nofollow noreferrer>

代码

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>

和以下CSS(用于放置工具提示)

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%);
 }

您的标签看起来像

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

,其中\b代表休息。请注意,如果您不想在x轴标签中留空格,则\n,\r,\t,\f ...将无法工作。如果您实际上希望有空格,请使用\n或其他内容并相应地更改RegEx

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/

这篇关于如何使工具提示内容显示在多行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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