使用 CSS 转换为 SVG 元素的位置设置动画

mat*_*ler 2 html javascript css svg

我想使用 CSS 转换来为 SVG 元素的位置设置动画。

但是 - 看起来这适用于某些 SVG 元素(例如,rect),但不适用于其他元素(例如文本):

document.querySelector("button").onclick = function() {
  var x = Math.random() * 450;
  document.querySelector("rect").setAttributeNS(null, "x", x);
  document.querySelector("text").setAttributeNS(null, "x", x);
}
Run Code Online (Sandbox Code Playgroud)
rect {
  transition: all 700ms ease-in-out;
}

text {
  transition: all 700ms ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)
<svg width="500" height="100">
  <rect x="100" y="10" width="30" height="30" fill="blue" stroke="none"/>
  <text x="100" y="80" fill="red" stroke="none">Hello</text>
</svg>
<br>
<button>animate</button>
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?有一个更好的方法吗?(理想情况下,不使用 JavaScript 或像 GreenSock 这样的库)。

Tem*_*fif 5

您可以改用翻译:

document.querySelector("button").onclick = function() {
  var x = Math.random() * 250;
  document.querySelector("rect").setAttributeNS(null, "transform","translate("+x+")");
  document.querySelector("text").setAttributeNS(null, "transform","translate("+x+")");
}
Run Code Online (Sandbox Code Playgroud)
rect {
  transition: all 700ms ease-in-out;
}

text {
  transition: all 700ms ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)
<svg width="500" height="100">
  <rect x="100" y="10" width="30" height="30" fill="blue" stroke="none"/>
  <text x="100" y="80" fill="red" stroke="none">Hello</text>
</svg>
<br>
<button>animate</button>
Run Code Online (Sandbox Code Playgroud)

  • 实际上,Chrome 与规范不一致。SVG 2 声明对于`&lt;text&gt;` x/y 属性是[不是表示属性](https://svgwg.org/svg2-draft/text.html#TSpanAttributes)。引用:“在 SVG 2 中,`text` 和 `tspan``x` 和 `y` 属性不是表示属性,不能通过 CSS 设置。” 背景是属性实际上接受 _lists_ 值。 (2认同)