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

如何修改ECharts自定义系列选中项的颜色?

问题解决:ECharts自定义系列选中/高亮样式不生效及api.style()标记废弃疑问

一、选中/高亮样式不生效的原因及解决方法

自定义系列(custom series)的渲染逻辑完全由开发者通过renderItem函数控制,ECharts不会自动将select、emphasis配置中的样式应用到你渲染的元素上。你需要手动在renderItem里判断当前项的状态,主动应用对应的样式。

具体修改步骤:

  • 在renderItem函数中,通过api.isSelected()判断当前项是否被选中,api.isEmphasis()判断是否处于高亮状态;
  • 根据状态优先级(选中 > 高亮 > 默认)合并样式;
  • 将合并后的样式赋值给渲染的rect元素。

修改后的renderItem示例代码:

renderItem: function (params, api) {
  // 判断当前项的选中/高亮状态
  const isSelected = api.isSelected();
  const isEmphasis = api.isEmphasis();

  // 合并样式:优先使用选中样式,其次高亮,最后默认
  let itemStyle = api.style();
  if (isSelected) {
    itemStyle = { ...itemStyle, fill: '#4338ca' };
  } else if (isEmphasis) {
    itemStyle = { ...itemStyle, fill: '#be123c' };
  }

  // 原有坐标计算逻辑
  const x = api.value(0);
  const y = api.value(1);
  const width = api.value(2);
  const height = api.value(3);
  const rectShape = api.coord([x, y, width, height]);

  return {
    type: 'rect',
    shape: rectShape,
    style: itemStyle
  };
}

同时确保已在系列配置中开启选中模式:

series: [{
  type: 'custom',
  selectedMode: 'single',
  // 其他配置...
}]

二、关于api.style()被标记废弃的疑问

VS Code或在线编辑器中的废弃提示来自ECharts的TypeScript类型定义(@types/echarts),目前官方文档存在更新滞后的情况。

实际上,ECharts 5及后续版本中,api.style()已被标记为废弃,官方推荐使用api.getStyle()替代,两者功能一致,只是命名更规范。你可以直接将api.style()替换为api.getStyle()来消除提示,同时保证代码的未来兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 11:36:04