更新时间:2023-12-04 12:52:40
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.
预览
代码
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/