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

AG-Grid实现跨行后行组颜色交替显示的方法

实现AG-Grid基于行组的交替颜色方案

核心思路

通过AG-Grid提供的getRowStyle或getRowClass回调函数,结合animal字段的分组特征,跟踪当前行所属的组,当组切换时交替应用颜色样式。

实现方案

方案1:直接通过getRowStyle设置背景色

无需额外CSS,直接在JS中定义颜色规则:

// 跟踪上一个分组的animal和当前颜色索引
let lastAnimal = null;
let colorIndex = 0;
// 定义交替的背景色数组
const rowGroupColors = ['#f5f5f5', '#ffffff'];

const gridOptions = {
  // 你的其他Grid配置(含跨行列定义)
  columnDefs: [
    {
      headerName: '列1',
      field: 'sort1',
      rowSpan: params => dagfuncs.rowSpanning1(params)
    },
    {
      headerName: '列2',
      field: 'animal',
      rowSpan: params => dagfuncs.rowSpanning2(params)
    },
    // 其他列配置...
  ],
  // 动态设置行样式
  getRowStyle: function(params) {
    const currentAnimal = params.data?.animal;
    // 当前行所属组与上一行不同时,切换颜色索引
    if (currentAnimal !== lastAnimal) {
      colorIndex = 1 - colorIndex;
      lastAnimal = currentAnimal;
    }
    return { backgroundColor: rowGroupColors[colorIndex] };
  }
};

方案2:通过getRowClass结合CSS类(更灵活)

先定义CSS类:

.row-group-light {
  background-color: #f5f5f5;
}
.row-group-white {
  background-color: #ffffff;
}

再在Grid配置中使用getRowClass分配类名:

let lastAnimal = null;
let classIndex = 0;

const gridOptions = {
  columnDefs: [
    // 你的跨行列定义...
  ],
  getRowClass: function(params) {
    const currentAnimal = params.data?.animal;
    if (currentAnimal !== lastAnimal) {
      classIndex = 1 - classIndex;
      lastAnimal = currentAnimal;
    }
    return classIndex === 0 ? 'row-group-light' : 'row-group-white';
  }
};

扩展:指定特定分组的颜色,其余自动交替

如果需要给dog、cat等特定分组设置专属颜色,其余分组自动交替:

// 特定分组的颜色映射
const specificAnimalColors = {
  dog: '#ffebee',
  cat: '#e3f2fd'
};
let lastAnimal = null;
let fallbackColorIndex = 0;
const fallbackColors = ['#f5f5f5', '#ffffff'];

const gridOptions = {
  getRowStyle: function(params) {
    const currentAnimal = params.data?.animal;
    // 优先使用指定颜色
    if (specificAnimalColors[currentAnimal]) {
      return { backgroundColor: specificAnimalColors[currentAnimal] };
    }
    // 无指定颜色的分组,自动交替
    if (currentAnimal !== lastAnimal) {
      fallbackColorIndex = 1 - fallbackColorIndex;
      lastAnimal = currentAnimal;
    }
    return { backgroundColor: fallbackColors[fallbackColorIndex] };
  }
};

注意事项

  • 若数据动态加载、排序或过滤,需要在数据更新时重置lastAnimal和索引变量,避免颜色逻辑混乱;
  • 跨行不会影响该颜色规则,因为getRowStyle/getRowClass会作用于每一行,跨行的单元格会继承所在行的样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:22:54