简体   繁体   中英

How to change event (hover & click) on legend item in highcharts?

You can see point value in the pie center if you are hovering chart points. Also you can see total value if you stop hovering chart point. It'd like the same behavior, if you're hovering legend item.

const chart = Highcharts.chart('container', {
  chart: {
    type: 'pie',
    events: {
        load: function(){
            this.title.attr({text: this.series[0].total});
        },
      render: function() {
        this.series && this.title.attr({y: this.plotHeight / 2 + this.plotTop + 5});
      }
    }
  },
  title: {
    text: ''
  },
  legend: {
    enabled: true,
  },
  plotOptions: {
    pie: {
    showInLegend: true,
      innerSize: '50%',
      dataLabels: {
        enabled: false
      },
      point: {
        events: {
          mouseOver: function() {
            this.series.chart.title.attr({text: this.y});
          },
          mouseOut: function(){
            this.series.chart.title.attr({text: this.total});
          },
        }
      }
    }
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
      name: 'Microsoft Internet Explorer',
      y: 56.33
    }, {
      name: 'Chrome',
      y: 24.03,
    }, {
      name: 'Firefox',
      y: 10.38
    }]
  }]
});

https://jsfiddle.net/q5fh1nog/24/

Also I want that clicking on active legend item will recalculate total value and show it in the center

在此处输入图像描述

You can add mouseover and mouseout event listeners on legend's elements and update the title in the same way as in point's events listeners. For example:

  chart: {
    type: 'pie',
    events: {
      load: function() {
        const series = this.series[0];
        this.title.attr({
          text: this.series[0].total
        });

        series.points.forEach(point => {
          ['label', 'symbol'].forEach(prop => {
            point.legendItem[prop].on('mouseover', () => {
              series.chart.title.attr({
                text: point.y
              });
            });

            point.legendItem[prop].on('mouseout', () => {
              series.chart.title.attr({
                text: point.total
              });
            });
          });
        });
      },
      ...
    }
  }

Live demo: https://jsfiddle.net/BlackLabel/kq9vL7so/

API Reference: https://api.highcharts.com/class-reference/Highcharts.SVGElement#on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM