Google Gantt Chart:状态颜色匹配异常及占位行隐藏问题求助
解决Google Gantt Chart颜色映射错位+隐藏占位行问题
方案一:用Style角色直接绑定状态与颜色(推荐)
彻底摆脱占位行和palette依赖任务顺序的问题,直接给每个任务指定对应颜色:
- 给DataTable添加
style角色列,示例代码:
const data = new google.visualization.DataTable(); data.addColumn('string', '任务名称'); data.addColumn('string', '任务状态'); data.addColumn('date', '开始日期'); data.addColumn('number', '时长'); // 添加style角色列,用于指定任务颜色 data.addColumn({type: 'string', role: 'style'});
- 定义状态-颜色映射表:
const statusColors = { '项目主线': '#2196F3', '逾期': '#F44336', '正常进行': '#4CAF50', '审核中': '#FFC107', '已完成': '#9E9E9E' };
- 构造任务数据时,直接从映射表取颜色填入style列:
// 示例任务行 data.addRows([ ['需求调研', '正常进行', new Date(2024, 3, 1), 7, statusColors['正常进行']], ['UI设计', '审核中', new Date(2024, 3, 8), 5, statusColors['审核中']], ['开发上线', '项目主线', new Date(2024, 3, 15), 10, statusColors['项目主线']] ]);
这种方式不管哪种状态有没有任务,颜色都不会错位,完全不需要占位行。
方案二:用DataView过滤占位行(兼容现有palette用法)
如果坚持用palette+占位行的方式,解决hideRows报错的问题:
Google Charts的DataTable没有hideRows()方法(该方法属于Google Sheets API),要隐藏行得用DataView过滤:
- 创建DataView,跳过前5-6行的占位行:
const view = new google.visualization.DataView(data); // 假设前5行是占位行,取第5行及以后的所有行 const visibleRows = Array.from({length: data.getNumberOfRows() - 5}, (_, idx) => idx + 5); view.setRows(visibleRows);
- 绘制图表时传入DataView而非原始DataTable:
const chart = new google.visualization.Gantt(document.getElementById('gantt_div')); chart.draw(view, options);
这样占位行不会显示,但依然存在于原始DataTable中,palette的颜色映射不会错位。
内容的提问来源于stack exchange,提问作者Daniel Pedley
相关产品推荐
相关产品推荐

