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

SVG <animate>标签values属性引用CSS变量的Chrome兼容方案咨询

问题描述

在SVG <animate> 标签中使用 values="var(--color1);var(--color2)" 的写法可在Firefox中正常运行,但在Chrome中无法生效,代码示例如下:

CSS代码

:root {
    --color1: #7F0000;
    --color2: #007F00;
}

SVG代码

<svg width="100" viewBox="-50 -50 100 100">
    <circle cx="0" cy="0" r="25" fill="var(--color1)">
        <animate attributeName="fill" dur="3s" values="var(--color1);var(--color2);var(--color1)" repeatCount="indefinite" />
    </circle>
</svg>
可行的解决办法

Chrome目前不支持在SVG animate的values属性中直接解析CSS变量,以下是两种可靠的替代方案:

方案一:改用CSS动画实现

将动画逻辑迁移到CSS中,借助@keyframes配合CSS变量,能在Chrome和Firefox中都正常运行:

:root {
    --color1: #7F0000;
    --color2: #007F00;
}

circle {
    fill: var(--color1);
    animation: colorCycle 3s infinite;
}

@keyframes colorCycle {
    0% { fill: var(--color1); }
    50% { fill: var(--color2); }
    100% { fill: var(--color1); }
}

对应的SVG可以移除<animate>标签:

<svg width="100" viewBox="-50 -50 100 100">
    <circle cx="0" cy="0" r="25" />
</svg>

方案二:用JavaScript动态赋值

如果必须保留SVG <animate> 标签,可以通过JS读取CSS变量的实际值,再动态设置values属性:

:root {
    --color1: #7F0000;
    --color2: #007F00;
}
<svg width="100" viewBox="-50 -50 100 100">
    <circle cx="0" cy="0" r="25" fill="var(--color1)">
        <animate id="colorAnim" attributeName="fill" dur="3s" repeatCount="indefinite" />
    </circle>
</svg>

<script>
// 获取根元素的CSS变量值
const rootStyles = getComputedStyle(document.documentElement);
const color1 = rootStyles.getPropertyValue('--color1').trim();
const color2 = rootStyles.getPropertyValue('--color2').trim();

// 为animate标签设置values属性
document.getElementById('colorAnim').setAttribute('values', `${color1};${color2};${color1}`);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:47:37