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

Highcharts鼠标悬停:高亮对应Y轴并弱化其余Y轴的实现问题

Highcharts多系列双侧Y轴:扩展mouseOver行为及自定义图例悬停效果

一、完善数据点/线条mouseOver时的Y轴标签效果

你已经实现了对应Y轴标签加粗,现在只需补充其余Y轴标签降低透明度的逻辑,同时在mouseOut时恢复所有Y轴的原始样式:

修改series的事件配置

在每个series的events中添加/完善mouseOver和mouseOut事件:

series: [{
  // 其他配置项...
  events: {
    mouseOver: function() {
      const currentYAxis = this.yAxis;
      const chart = this.chart;

      // 遍历所有Y轴,设置对应样式
      chart.yAxis.forEach(axis => {
        if (axis === currentYAxis) {
          // 对应Y轴标签加粗,保持完全不透明
          axis.axisLabel.attr({ 'font-weight': 'bold' });
          axis.update({
            labels: { style: { opacity: 1 } }
          }, false); // false:暂不重绘
        } else {
          // 其余Y轴标签降低透明度
          axis.update({
            labels: { style: { opacity: 0.3 } }
          }, false);
        }
      });
      chart.redraw(false); // 统一重绘,提升性能
    },
    mouseOut: function() {
      const chart = this.chart;

      // 恢复所有Y轴的原始样式
      chart.yAxis.forEach(axis => {
        axis.axisLabel.attr({ 'font-weight': 'normal' });
        axis.update({
          labels: { style: { opacity: 1 } }
        }, false);
      });
      chart.redraw(false);
    }
  }
},
// 其他系列同理...
]

二、自定义图例鼠标悬停行为

通过配置legend的itemMouseOver和itemMouseOut事件,可实现图例悬停时的自定义交互(比如高亮对应系列&Y轴,灰化其他元素):

修改legend配置

legend: {
  // 其他配置项...
  itemMouseOver: function(e) {
    const targetSeries = e.target;
    const targetYAxis = targetSeries.yAxis;
    const chart = targetSeries.chart;

    // 遍历所有系列,设置悬停状态
    chart.series.forEach(series => {
      if (series === targetSeries) {
        // 高亮当前系列
        series.setState('hover');
        // 对应Y轴标签加粗、保持不透明
        targetYAxis.axisLabel.attr({ 'font-weight': 'bold' });
        targetYAxis.update({ labels: { style: { opacity: 1 } } }, false);
      } else {
        // 灰化其他系列
        series.setState('inactive');
        // 其他Y轴标签降低透明度
        series.yAxis.update({ labels: { style: { opacity: 0.3 } } }, false);
      }
    });
    chart.redraw(false);
  },
  itemMouseOut: function(e) {
    const chart = e.target.chart;

    // 恢复所有系列和Y轴的原始状态
    chart.series.forEach(series => {
      series.setState('');
      series.yAxis.axisLabel.attr({ 'font-weight': 'normal' });
      series.yAxis.update({ labels: { style: { opacity: 1 } } }, false);
    });
    chart.redraw(false);
  }
}

说明

  • 使用setState('hover')和setState('inactive')可以快速切换系列的高亮/灰化状态,这是Highcharts内置的状态管理方式
  • 所有update操作传入false,最后统一调用chart.redraw(false),避免频繁重绘导致的性能问题
  • 透明度值(0.3)可根据需求自行调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:40:53