诀窍是像这样使用 x 轴标签对象:
xAxis: {
type: 'datetime',
labels: {
useHTML: true,
align: 'center',
formatter: function () {
//using a specific class for the labels helps to ensure no other labels are moved
return '<span class="timeline_label">' + Highcharts.dateFormat(this.dateTimeLabelFormat, this.value) + '</span>';
}
}
您可以看到格式化程序将保留用户设置或默认设置的任何 dateTimeLabelFormat。
然后有一个回调,做这样的事情:
function (chart) {
var $container = $(chart.container);
var $labels = $container.find('.highcharts-axis-labels .timeline_label');
var $thisLabel, $nextLabel, thisXPos, nextXPos, delta, newXPos;
$labels.each(function () {
$thisLabel = $(this).parent('span');
thisXPos = parseInt($thisLabel.css('left'));
$nextLabel = $thisLabel.next();
nextXPos = $nextLabel.length ? parseInt($nextLabel.css('left')) : chart.axes[0].left + chart.axes[0].width;
delta = (nextXPos - thisXPos) / 2.0;
newXPos = thisXPos + delta;
if ($nextLabel.length || $(this).width() + newXPos < nextXPos) {
$thisLabel.css('left', newXPos + 'px');
} else {
$thisLabel.remove();
}
});
});
简而言之,这将遍历每个标签并通过计算其自身与下一个标签之间的距离来确定它应该被移动多少(使用 css)。当它到达最后一个标签时,它要么使用轴的末端移动它以进行计算,要么如果它不适合则将其移除。这最后一部分只是我决定做的决定,你可能会选择做一些其他的事情,比如自动换行等等。
你可以看到jsfiddle here
希望这对某些人有所帮助。另外,如果有任何改进,很高兴在这里看到它们。