Highcharts使用格式化程序更改工具提示日期时间

时间:2019-02-06 23:58:21

标签: javascript highcharts tooltip momentjs

我有一个如下图所示的图形。默认情况下,每个工具提示值都在其自己的工具提示“气泡”中,日期时间位于Y轴的底部(悬停在X标签的顶部)。

default tooltip

问题在于Highcharts无法动态更改日期时间的格式以匹配语言环境。我知道我可以让用户更改dateTimeLabelFormats来匹配他们的语言环境,但是我正在寻找利用moment.js及其内置的语言环境格式。

我只需要更改这些图表中的日期时间就可以了。

当我在下面尝试此代码时,它为我提供了所需的语言环境杠杆,但是工具提示被合并为1个框,并且没有默认的感觉。

tooltip: {
    enabled: true,
    dateTimeLabelFormats: {
        //minute: '%e %b %H:%M',
        hour: '%e %b %H:%M'
    },
    // For locale control with moment. Combined momentjs with this answer https://stackoverflow.com/a/33939715/1177153
    formatter: function() {
        var toolTipTxt = '<b>'+ moment.unix(this.x / 1000).format("LLL") +'</b>';  
          $.each(this.points, function(i, point) {
            toolTipTxt += '<br/><span style="color:'+ point.series.color +'">  ' + point.series.name + ': ' + point.y+'</span>';
        });
        return toolTipTxt;
    },
    crosshairs: true,
    shared: true
},

moment.js locale formatting

是否可以使用格式化程序来模拟默认工具提示?值的各个“气泡”和底部的时间戳徘徊?

是否可以将xDateFormat与moment.js一起使用?

1 个答案:

答案 0 :(得分:2)

我从Highcharts API documentation for tooltip split开始找到了一个可行的解决方案。

jsfiddle example from the API documentation拥有我需要的一切(moment.js除外)。

我今天一定忽略了100次。这是对我有用的最终代码,以及结果的屏幕截图。

现在,工具提示的标题将位于正确的语言环境中,而无需用户更改任何代码。

tooltip: {
    enabled: true,
    // For locale control with moment.js - https://api.highcharts.com/highcharts/tooltip.split
    formatter: function () {
        // The first returned item is the header, subsequent items are the points
        return [moment.unix( this.x / 1000).format("LLL")].concat(
            this.points.map(function (point) {
                return "<span style='color:" + point.series.color + "'>\u25CF</span> " + point.series.name + ': ' + point.y;
            })
        );
    },
    split: true,
},

enter image description here

相关问题