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

如何通过JavaScript获取wrapper元素的--main-color CSS变量值?

获取CSS自定义变量值的正确方法

你的问题出在获取变量的目标元素不对——你定义的--main-color是在.wrapper元素的行内样式里,而不是根元素document.documentElement上,所以用根元素去拿肯定取不到。

正确的获取方式

  1. 先选中目标.wrapper元素
  2. 用getComputedStyle()方法获取该元素的计算样式,再从中提取变量值

示例代码:

// 选中wrapper元素
const wrapper = document.querySelector('.wrapper');
// 获取该元素的计算样式
const computedStyle = getComputedStyle(wrapper);
// 提取--main-color变量值,trim()去除可能的前后空格
const mainColor = computedStyle.getPropertyValue('--main-color').trim();

// 测试输出
console.log(mainColor); // 会输出#123456(或对应设置的颜色值)

根据颜色值切换图片的示例

拿到颜色值后,就可以按预设的映射关系设置图片:

// 定义颜色与图片的对应关系
const colorImageMap = {
  '#ff0000': 'red-img.png',
  '#00ff00': 'green-img.png',
  '#123456': 'custom-img.png'
};

// 获取需要设置图片的元素(假设是页面中的img标签)
const targetImg = document.querySelector('.target-img');
// 根据颜色值设置图片,没有匹配项时用默认图
targetImg.src = colorImageMap[mainColor] || 'default-img.png';

补充说明

  • 如果页面存在多个.wrapper元素,querySelector只会获取第一个,需要处理全部的话,改用querySelectorAll遍历即可
  • getComputedStyle能获取元素最终生效的所有样式,包括行内定义的CSS变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 08:02:02