highcharts自定义toolTip显示格式,显示传入series.data之外的数据 | 掘金年度征文

1,419 阅读1分钟

原文首发地址:github.com/Daotin/fe-b… 你也可以从下面地方找到我:


假如有如下场景,series.data传入的是处理后百分比数据:

// 维度1:得分1,总分2
// 维度2:得分4,总分10
// 维度1:得分6,总分10

Highcharts.chart('container', {
    title: {
        text: 'Demo'
    },
    xAxis: {
        categories: ['维度1', '维度2', '维度3'],
    },
    yAxis: {
      min: 0,
      max: 100,
    },
    tooltip: {
        pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}%</b><br/>',
        shared: true
    },

    series: [{
        name: '维度分类',
        data: [50,40,60]
    }]
});

这样每个点的tip显示都是传入的data的百分比数据。

现在有个需求,我想让点的tip显示的是分数,而不是百分比,怎么办呢?

由于传入的是series.data之外的数据,所以我们不能使用pointFormat属性或者pointFormatter方法,因为这两个都是对传入的data数据进行变形处理。

formatter方法可以解决我们问题:

思路如下:formatter方法里面我们可以拿到当前point点的值和其在data数组的索引index,然后把维度分组成数组,该数组的index位置就是当前point值的维度分。

局部代码如下:

tooltip: {
    shared: true,
    // pointFormat: '<span style="color:{series.color}">{series.name}: <b>{point.y:,.0f}%</b><br/>',
    formatter: function () {
        return this.points.reduce(function (s, point) {
            return s + '<br/>' +
                `<span style="color:${point.series.color}">${point.series.name}</span>` + ': ' + me.catescore[point.point.index] + '分';
        }, '<b>' + this.x + '</b>');
    },
},

可能有人疑问,为什么不直接给series.data传入维度的分数而传入百分比?

因为维度的总分参差不齐,我想都把维度都转化成百分制的形式(yAxis设置了min和max),这样整体显示美观一些。

参考链接:

掘金年度征文 | 2020 与我的技术之路 征文活动正在进行中......