我创建了一个简单的 SVG 动画,通过单击 SVG 元素来触发。我想多次重复使用这个动画元素,并希望避免每次都重复定义。但是,当我在 a 中创建元素时<defs>
标签,然后用<use>
标签,我无法从外部访问动画。
下面是同一动画元素的示例,该元素既独立(黄色)又作为<use>
元素(橙色和红色)。唯一有效的动画是黄色的。
我在 SVG 中包含了重复动画g
组内定义<defs>
部分,以表明动画确实有效。
有没有办法在a中触发动画<use>
来自外部的元素?或者是否有另一种方法可以在重复使用的元素内创建 2 状态动画?
jsfiddle http://jsfiddle.net/m1epsL8h/1/
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
g#yellow {
fill:#cc9;
color: #993;
}
use#orange {
fill: #ca8;
color: #963;
}
use#red {
fill:#c99;
color:#933;
}
</style>
</head>
<body>
<svg width="360" height="120"
viewPort="0 0 120 360" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<g
id="door"
width="120"
height="120"
viewPort="0 0 120 120">
<rect width="120" height="120" class="wall"></rect>
<rect
x="30"
y="20"
width="60"
height="100"
fill="#000"
opacity="0.7"></rect>
<polygon class="door"
points="
30,120
90,120
90,20
30,20"
fill="currentColor">
<animate
class="open"
attributeName="points"
dur="500ms"
to="
100,120
90,120
90,20
100,10"
begin="indefinite"
fill="freeze" />
<animate
class="shut"
attributeName="points"
dur="500ms"
to="
30,120
90,120
90,20
30,20"
begin="indefinite"
fill="freeze" />
<animate
attributeName="opacity"
values="0.5;1;0.5" dur="2s"
repeatCount="indefinite" />
</polygon>
</g>
</defs>
<use x="240" y="0" xlink:href="#door" id="red"/>
<use x="120" y="0" xlink:href="#door" id="orange"/>
<g xlink:href="#door" id="yellow"
id="door"
width="120"
height="120"
viewPort="0 0 120 120">
<rect width="120" height="120" class="wall"></rect>
<rect
x="30"
y="20"
width="60"
height="100"
fill="#000"
opacity="0.7"></rect>
<polygon class="door"
points="
30,120
90,120
90,20
30,20"
fill="currentColor">
<animate
class="open"
attributeName="points"
dur="500ms"
to="
100,120
90,120
90,20
100,10"
begin="indefinite"
fill="freeze" />
<animate
class="shut"
attributeName="points"
dur="500ms"
to="
30,120
90,120
90,20
30,20"
begin="indefinite"
fill="freeze" />
</polygon>
</g>
</svg>
<script>
;(function () {
document.body.onclick = function(event) {
var target = event.target
var animation
while (target && target.nodeName.toLowerCase() !== "g") {
target = target.parentNode
}
if (!target) {
return
}
if (target.classList.contains("open")) {
target.classList.remove("open")
animation=document.querySelector("#"+target.id+" animate.shut")
} else {
target.classList.add("open");
animation=document.querySelector("#"+target.id+" animate.open")
}
animation.beginElement()
}
})()
</script>
</body>
</html>
编辑:我尝试了另一种方法,我定义了几种不同的方法g
要素:
- 一个没有动画的
- 一个带有开场动画的
- 一个带有关闭动画的
我使用 JavaScript 来交换href
of <use>
元素到适当的g
元素。
交换元素无法播放动画,在不同浏览器中效果不同。在 Chrome 和 Firefox 中,新元素会立即出现在动画后状态中。在 Apple Safari 中,它们显示为动画前状态。
jsfiddle http://jsfiddle.net/xocxk8hc/