Highcharts结合Datatables时自定义配置未生效及参数添加问题
问题
我同时使用Datatables与Highcharts,用户点击2023、2022及ABC按钮时,图表可重载并展示动画,功能正常。但为柱状图chart-A设置的特定配置(如边框样式、提示框格式、坐标轴样式等)并未生效,请问为何这些配置无法应用?同时想了解如何为从Datatables拉取数据的Highcharts添加额外参数。
相关配置代码:
var myChart = Highcharts.chart("chart-A", { chart: { type: "column", borderColor: 'lightgray', borderWidth: 1, marginTop: 50 }, tooltip: { headerFormat: '{point.key}<br/>', pointFormat: '{series.name}: <b>{point.y:.1f}%</b>' }, legend: { symbolRadius: 0, itemStyle: { color: '#000000', fontSize: '16px' } }, colors: ['#003489', '#ED7D31', '#A5A5A5', '#FFC000', '#5B9BD5'], credits: { enabled: false }, title: { text: "Top Seven OCC Award Trends" }, xAxis: { categories: categories, labels: { style: { fontWeight: '600', fontSize: '16px', color: '#000000' } } }, yAxis: { title: false, tickInterval: 10, max: 60, labels: { formatter: function () { return Highcharts.numberFormat(this.value, 0); }, style: { fontWeight: '600', fontSize: '16px', color: '#000000' } } }, series: allSeriesData });
解答
一、自定义配置未生效的原因及解决办法
自定义配置被覆盖:页面加载时你初始化了带有完整样式的chart-A,但随后Datatables的drawCallback回调中又重新创建了一次chart-A,且这次创建仅传入了series、xAxis等基础配置,未包含边框、提示框、坐标轴样式等自定义内容,导致原有配置被覆盖失效。
解决步骤:
- 抽离所有自定义配置为全局对象,避免重复编写:
const chartBaseOptions = { chart: { type: "column", borderColor: 'lightgray', borderWidth: 1, marginTop: 50 }, tooltip: { headerFormat: '{point.key}<br/>', pointFormat: '{series.name}: <b>{point.y:.1f}%</b>' }, legend: { symbolRadius: 0, itemStyle: { color: '#000000', fontSize: '16px' } }, colors: ['#003489', '#ED7D31', '#A5A5A5', '#FFC000', '#5B9BD5'], credits: { enabled: false }, title: { text: "Top Seven OCC Award Trends" }, yAxis: { title: false, tickInterval: 10, max: 60, labels: { formatter: function () { return Highcharts.numberFormat(this.value, 0); }, style: { fontWeight: '600', fontSize: '16px', color: '#000000' } } } };
- 统一使用该基础配置创建/更新图表:
- 首次初始化:
var myChart = Highcharts.chart("chart-A", { ...chartBaseOptions, xAxis: { categories: categories, labels: { style: { fontWeight: '600', fontSize: '16px', color: '#000000' } } }, series: allSeriesData });
drawCallback中改用update方法更新数据,不再重新创建图表:
drawCallback: function(settings) { // 处理得到categories和allSeriesData myChart.update({ xAxis: { categories: categories, labels: { style: { fontWeight: '600', fontSize: '16px', color: '#000000' } } }, series: allSeriesData }); }
二、为从Datatables拉取数据的Highcharts添加额外参数
可通过两种方式实现:
- 数据处理阶段添加自定义参数:
从Datatables提取数据生成series时,直接为series对象添加自定义属性:
// 处理Datatables数据生成series示例 const customSeries = { name: seriesName, data: seriesData, // 自定义参数 customTag: "年度数据", highlightColor: "#ff0000" };
后续可通过myChart.series[index].options.customTag访问该参数。
- 图表配置中添加全局自定义参数:
直接在图表配置对象中加入全局自定义项:
var myChart = Highcharts.chart("chart-A", { ...chartBaseOptions, // 全局自定义参数 globalConfig: { filterType: "year", currentFilter: "2023" }, xAxis: { /* ... */ }, series: allSeriesData });
后续可通过myChart.options.globalConfig访问该配置。
内容的提问来源于stack exchange,提问作者newuser
相关产品推荐
相关产品推荐

