You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Highcharts图例项的hover与click事件实现指定交互

实现饼图图例hover交互与点击更新中心总值

核心修改点

  • 给图例添加鼠标进出交互,匹配对应数据点后更新中心文本
  • 封装统一的总值计算逻辑,复用在鼠标离开、图例点击等场景
  • 点击已激活(显示状态)的图例项时,重新计算当前可见数据的总和并更新中心文本

修改后的完整代码

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,
    // 图例鼠标悬浮事件
    itemMouseOver: function(e) {
      const targetPoint = e.target;
      targetPoint.series.chart.title.attr({text: targetPoint.y});
    },
    // 图例鼠标离开事件
    itemMouseOut: function(e) {
      const currentChart = e.target.series.chart;
      // 计算当前可见数据的总值
      const visibleTotal = currentChart.series[0].points.reduce((sum, point) => {
        return point.visible ? sum + point.y : sum;
      }, 0);
      currentChart.title.attr({text: visibleTotal.toFixed(2)});
    },
    // 图例点击事件
    itemClick: function(e) {
      const currentChart = e.target.series.chart;
      // 延迟获取最新可见状态,避免Highcharts状态更新延迟
      setTimeout(() => {
        const visibleTotal = currentChart.series[0].points.reduce((sum, point) => {
          return point.visible ? sum + point.y : sum;
        }, 0);
        currentChart.title.attr({text: visibleTotal.toFixed(2)});
      }, 0);
    }
  },
  plotOptions: {
    pie: {
      showInLegend: true,
      innerSize: '50%',
      dataLabels: {
        enabled: false
      },
      point: {
        events: {
          mouseOver: function() {
            this.series.chart.title.attr({text: this.y});
          },
          mouseOut: function(){
            const currentChart = this.series.chart;
            // 复用可见总值计算逻辑
            const visibleTotal = currentChart.series[0].points.reduce((sum, point) => {
              return point.visible ? sum + point.y : sum;
            }, 0);
            currentChart.title.attr({text: visibleTotal.toFixed(2)});
          },
        }
      }
    }
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
      name: 'Microsoft Internet Explorer',
      y: 56.33
    }, {
      name: 'Chrome',
      y: 24.03,
    }, {
      name: 'Firefox',
      y: 10.38
    }]
  }]
});

关键逻辑说明

  • 图例hover交互:通过itemMouseOver直接获取对应数据点,显示其数值;鼠标离开时计算当前所有可见数据的总和,用toFixed(2)保证数值格式统一
  • 图例点击更新:利用setTimeout规避Highcharts状态更新的延迟问题,确保获取到最新的点可见状态后计算总值
  • 统一总值计算:使用数组reduce方法遍历所有数据点,只累加可见点的数值,保证隐藏部分数据时中心显示的是当前有效总值

内容的提问来源于stack exchange,提问作者Kvasimodo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:20:14