问题
I'm trying to make the tooltip's background color match the line's color using Highcharts.
I'm trying to find the most reasonable native way to handle this -- if it's possible to avoid adding a <div />
with a background color to the formatter, that would be great - but if not I guess that works too.
The lines colors & amount will change a lot so I don't wanna hard-code the background colors the same way I put the line colors - if they could draw the background the same as the line color, that would be great.
My only idea didn't work, I'm not sure what the scope for these functions is in this case:
tooltip : {
backgroundColor: function() {
return this.line.color;
//return this.point.color;
}
}
My line colors are set normally:
series : [
{
color : '#fa0'
}
]
Any ideas?
Thanks in advance.
回答1:
It's not possible to set this in other way than using formatter. Only something like this: http://jsfiddle.net/GGQ2a/2/
JS:
tooltip: {
useHTML: true,
backgroundColor: null,
borderWidth: 0,
shadow: false,
formatter: function(){
return '<div style="background-color:' + this.series.color + '" class="tooltip"> ' +
this.series.name + '<br>' + this.key + '<br>' + this.y +
'</div>';
}
},
And CSS:
.tooltip {
padding: 5px;
border-radius: 5px;
box-shadow: 2px 2px 2px;
}
回答2:
You can also try too hook up to mouseOver
event.
Advantage of this solution over the one of Paweł Fus is that you can keep the width of tooltip which is necessary for nice anchor thing.
Reference: https://api.highcharts.com/highcharts/plotOptions.series.events.mouseOver
plotOptions: {
series: {
stickyTracking: false,
events: {
mouseOver() {
const color = arguments[0].target.color;
this.chart.tooltip.options.backgroundColor = color; //first time overwrite
const tooltipMainBox = document.querySelector(`g.highcharts-tooltip path:last-of-type`);
if (tooltipMainBox) {
tooltipMainBox.setAttribute('fill', color);
}
}
}
}
}
jsFiddle: http://jsfiddle.net/ymdLzzkb/1/
回答3:
Old question, but an alternate way to do this is to hook the tooltipRefresh
event and swap in with some jquery
. Working code:
$(function () {
$('#container').highcharts({
chart: {
type:'column',
events: {
tooltipRefresh: function(e) {
if (!e.target.hoverSeries) return;
$('.highcharts-tooltip>path:last-of-type')
.css('fill', e.target.hoverSeries.color);
}
}
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
},{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
来源:https://stackoverflow.com/questions/18742013/highcharts-tooltip-background-according-to-line