SVG <animate> 标签的值属性可以引用 CSS 变量吗?

问题描述 投票:0回答:3

在 SVG

values="var(--color1);var(--color2)"
标签中使用
<animate>
在 Firefox 中有效,但在 Chrome 中无效(参见下面的代码片段)。有没有办法让它在 Chrome 中工作?

:root {
    --color1: #7F0000;
    --color2: #007F00;
}
<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>

html svg cross-browser svg-animate
3个回答
0
投票

最简单的 解决方法 是原生 JavaScript Web 组件

类似的东西

getComputedStyle(this).getPropertyValue("--color1")
读取 CSS 值

customElements.define("svg-circle", class extends HTMLElement {
  connectedCallback() {
    this.style.display = "inline-block";
    let c1 = this.getAttribute("color1") || "lightgoldenrodyellow";
    let c2 = this.getAttribute("color2") || "rebeccapurple";
    this.innerHTML = `<svg width="180" viewBox="-50 -50 100 100">
    <circle r="49">
     <animate attributeName="fill" dur="3s" values="${c1};${c2};${c1}" repeatCount="indefinite"/>
    </circle></svg>`;
  }
});
<svg-circle></svg-circle>
<svg-circle color1="gold"></svg-circle>
<svg-circle color1="red" color2="green"></svg-circle>


0
投票

您可以将 SMIL 动画替换为使用 Web Animations API 完成的动画。

const circle01 = document.getElementById('circle');

var circleKeyframes = new KeyframeEffect(
  circle01, [{
      fill: 'var(--color1)'
    },
    {
      fill: 'var(--color2)'
    }
  ], {
    duration: 3000,
    iterations: Infinity
  }
);

var a1 = new Animation(circleKeyframes, document.timeline);
a1.play();
:root {
  --color1: #7F0000;
  --color2: #007F00;
}

circle {
  fill: var(--color1);
}
<svg width="100" viewBox="-50 -50 100 100">
  <circle id="circle" cx="0" cy="0" r="25" />
</svg>


0
投票

很容易用纯 CSS 制作动画。

:root {
    --color1:#7F0000;
    --color2:#007F00;
}
#aCircle{
    animation:test 3s linear 0s infinite;
}
@keyframes test{
    0% {fill:var(--color1);}
    50% {fill:var(--color2);}
    100% {fill:var(--color1);}
}
<svg width="100" viewBox="-50 -50 100 100">
    <circle id="aCircle" cx="0" cy="0" r="25" style="fill:var(--color1);"/>
</svg>

© www.soinside.com 2019 - 2024. All rights reserved.