use:
Элемент берет узлы из документа SVG и дублирует их где-то еще. - mdn
Так что использовать use
бесполезно, поскольку вы не дублируете его.
(() => {
setTimeout(() => {
const rect1 = document.getElementById('rect-1');
rect1.classList.add('grow');
const rect2 = document.getElementById('rect-2');
rect2.classList.add('grow');
}, 1000);
})();
.grow {
-webkit-transition: 1.5s;
-moz-transition: 1.5s;
-o-transition: 1.5s;
transition: width 3s;
width: 10px;
}
<!-- works -->
<svg width="400" height="100">
<rect id="rect-1" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
<svg width="400" height="100">
<rect id="rect-2" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
Обновление 1
Даже SVG <animate>
не работает в FireFox, когда элемент дублируется. Хотя, если не используется внутри обновленного элемента. Это известная проблема. Есть много вопросов без ответа о стеке потока, например этот .
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use -->
<svg viewBox="0 0 30 10" xmlns="http://www.w3.org/2000/svg">
<circle id="myCircle" cx="5" cy="5" r="4" stroke="blue"/>
<use href="#myCircle" x="10" fill="blue"/>
<use href="#myCircle" x="20" fill="white" stroke="red"/>
<!--
stroke="red" will be ignored here, as stroke was already set on myCircle.
Most attributes (except for x, y, width, height and (xlink:)href)
do not override those set in the ancestor.
That's why the circles have different x positions, but the same stroke value.
-->
<animate
xlink:href="#myCircle"
attributeName="r"
from="4"
to="2"
dur="5s"
begin="0s"
repeatCount="1"
fill="freeze"
id="circ-anim"/>
</svg>
Обновление 2
Анимации на элементе, на который есть ссылка, также приводят к анимации экземпляров. use - w3
Согласно документации, если вы анимируете связанный элемент (`myCircle), все его дубликаты также должны быть анимированы. Так что я думаю, это ошибка, что она не работает в Firefox & Safari.
Обновление 3 - обходной путь
Используйте тег svg <animate>
и заключите его в <rect>
.
<svg width="400" height="400">
<defs>
<g id="my-rect">
<rect id="rect-2" width="400" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)">
<animate
attributeName="width"
from="400"
to="10"
dur="3s"
begin="1s"
repeatCount="1"
fill="freeze"
id="rect-2"/>
</rect>
</g>
</defs>
<use xlink:href="#my-rect" y="0"/>
<use xlink:href="#my-rect" y="110"/>
</svg>