当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Highcharts Line Chart - Highlight xAxis labels on point hover

问题描述:

Faced with a problem of highlighting labels in the line chart.

I found here a similar theme Bold X-Axis Label on Point Hover in Highcharts Column Chart, but it's not suitable (didn't find any information about xAxis[0].labelGroup in that case). Also there's no information in documentation

What I need:

Highlight labels on xAxis on point hover effect, and it should highlight the closest one. Type of the axis is datetime, and the interval is 6 hours

My example:

https://jsfiddle.net/sjapdya6/

I was trying to use:

 mouseOver: function() {

$($('.customLabel')[this.x]).addClass('customLabelSelected');

}

Adding these classes:

<style>

.customLabel {

color: #00FF00;

background-color: rgba(10, 10, 90, 0.8);

}

.customLabelSelected {

color: #FF0000;

}

</style>

But it doesn't work properly.

Does anybody know how to achieve this?

Many thanks in advance

网友答案:

Axis holds an object called ticks and the ticks within that object are identified by its value on the axis. The part of the tick object is the label you want to style.

So you need to find the 'close enough' tick for the hovered point. The points do not have exactly the same values as the ticks, so you need to define the distance which satisfies you.

function findTick(x, ticks, range) {
  for (var tickValue in ticks) {
    if (Math.abs(x - tickValue) <= range) {
      return ticks[tickValue];
    }
  }
}

Events for points which will take the proper actions:

events: {
      mouseOver: function(e) {
        var tick = findTick(this.x, this.series.xAxis.ticks, 300000);
        this.selectedTick = tick;

        if (tick) {
          tick.label.css({
            color:'#FF0000'
          });
        }
      },
      mouseOut: function(e) {
        if (this.selectedTick) {
          this.selectedTick.label.css({
            color: '#565f76'
          });
          this.selectedTick = null;
        }
      }
    }

Last thing, if you want to use css styling, then you have to enabled html labels.

   labels: {
    useHTML: true,

Otherwise, you would operate on svg elements which styles property are different than styles for html elements.

example: https://jsfiddle.net/sjapdya6/1/

分享给朋友:
您可能感兴趣的文章:
随机阅读: