javascript
// 获取指定的css变量
const getCssVariable = (name) =>{
return getComputedStyle(document.documentElement).getPropertyValue(name).trim()
}
// 使用示例
const primaryColor = getCssVariable ('--chart-primary-rgb') // rgba(24, 144, 255, 0.5)
加透明度
javascript
const getCssVariableWithOpacity = (name, opacity = 1) => {
const rgbValue = getComputedStyle(document.documentElement)
.getPropertyValue(name)
.trim()
if (!rgbValue) return ''
// 如果传入的是 rgba 字符串,直接修改透明度
if (rgbValue.startsWith('rgba')) {
return rgbValue.replace(/[\d.]+\)$/g, `${opacity})`)
}
// 如果是 RGB 数值格式(如 "24, 144, 255")
return `rgba(${rgbValue}, ${opacity})`
}
// 使用示例
const primaryColor = getCssVariableWithOpacity('--chart-primary-rgb', 0.5) // rgba(24, 144, 255, 0.5)