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

Chart.js明暗模式切换问题:图表标签颜色无法同步更新

解决Chart.js明暗模式切换时样式不更新的问题

你的判断是对的:Chart.js初始化时会一次性读取CSS变量的值,之后不会自动监听样式变化,所以切换明暗模式后图表样式不会更新。以下是具体的解决步骤:


1. 封装获取CSS变量的函数

先把读取根元素样式的逻辑封装成函数,方便后续重复调用:

function getRootVar(varName) {
  const root = document.querySelector(':root');
  return getComputedStyle(root).getPropertyValue(varName).trim();
}

2. 初始化Chart时使用函数动态取值

修改你的Chart初始化代码,用上面的函数替代直接赋值:

const labels = dates.map(date => moment(date).format('MM/DD/YYYY hh:mm:ss A'));
const ctx = document.getElementById('myChart').getContext('2d');
const mainColor = getRootVar('--app-content-main-color');

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: labels,
    datasets: [{
      label: 'Solar Power (W)',
      data: {{ solarPower|tojson }},
      backgroundColor: 'rgba(251, 99, 88, 0.2)',
      borderColor: 'rgba(251, 99, 88, 1)',
      borderWidth: 1
    }, {
      label: 'Battery Voltage (V)',
      data: {{ batteryVoltage|tojson }},
      backgroundColor: 'rgba(96, 177, 237, 0.2)',
      borderColor: 'rgba(96, 177, 237, 1)',
      borderWidth: 1
    }, {
      label: 'Load Power (W)',
      data: {{ batteryVoltage|tojson }},
      backgroundColor: 'rgba(56, 218, 91, 0.2)',
      borderColor: 'rgba(56, 218, 91, 1)',
      borderWidth: 1,
      fontColor: 'white'
    }, {
      label: 'Solar Voltage (V)',
      data: {{ solarVoltage|tojson }},
      backgroundColor: 'rgba(250, 112, 225, 0.2)',
      borderColor: 'rgba(250, 112, 225, 1)',
      borderWidth: 1
    }, {
      label: 'Solar Current (A)',
      data: {{ solarCurrent|tojson }},
      backgroundColor: 'rgba(77,219,255, 0.2)',
      borderColor: 'rgba(77,219,255, 1)',
      borderWidth: 1,
      color: mainColor
    }]
  },
  options: {
    scales: {
      xAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Date and Time',
          fontSize:14,
          fontColor: mainColor
        },
        ticks: {
          fontColor: mainColor,
          beginAtZero: true
        }
      }],
      yAxes: [{
        scaleLabel: {
          display: true,
          labelString: 'Values',
          fontSize:14,
          fontColor: mainColor
        },
        ticks: {
          beginAtZero: true,
          fontColor: mainColor
        }
      }]
    }
  }
});

3. 监听模式切换事件并更新图表

给你的明暗模式切换按钮添加事件监听,在切换时重新读取CSS变量,更新Chart配置后强制渲染:

// 假设切换按钮的ID是mode-switch
document.getElementById('mode-switch').addEventListener('click', () => {
  const newMainColor = getRootVar('--app-content-main-color');

  // 更新数据集里的文本颜色
  myChart.data.datasets.forEach(dataset => {
    if (dataset.color) dataset.color = newMainColor;
  });

  // 更新坐标轴刻度和标签颜色
  myChart.options.scales.xAxes.forEach(axis => {
    axis.scaleLabel.fontColor = newMainColor;
    axis.ticks.fontColor = newMainColor;
  });
  myChart.options.scales.yAxes.forEach(axis => {
    axis.scaleLabel.fontColor = newMainColor;
    axis.ticks.fontColor = newMainColor;
  });

  // 如果有图例,同步更新图例颜色
  if (myChart.options.legend) {
    myChart.options.legend.labels.fontColor = newMainColor;
  }

  // 强制Chart重新渲染
  myChart.update();
});

可选:自动监听根元素类变化

如果你的明暗模式是通过给根元素添加/移除类(比如.dark-mode)实现的,可以用MutationObserver自动监听类变化,无需绑定按钮事件:

const root = document.querySelector(':root');
const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    if (mutation.attributeName === 'class') {
      // 类变化时触发图表更新
      const newMainColor = getRootVar('--app-content-main-color');
      // 下面的更新逻辑和上面按钮事件里的一致
      myChart.data.datasets.forEach(dataset => {
        if (dataset.color) dataset.color = newMainColor;
      });
      myChart.options.scales.xAxes.forEach(axis => {
        axis.scaleLabel.fontColor = newMainColor;
        axis.ticks.fontColor = newMainColor;
      });
      myChart.options.scales.yAxes.forEach(axis => {
        axis.scaleLabel.fontColor = newMainColor;
        axis.ticks.fontColor = newMainColor;
      });
      if (myChart.options.legend) {
        myChart.options.legend.labels.fontColor = newMainColor;
      }
      myChart.update();
    }
  });
});

observer.observe(root, { attributes: true });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:57:55