首页 > 解决方案 > SVG 动画:tspan 翻译

问题描述

我正在尝试在悬停时为 svg 的每个字母设置一个文本元素(制作然后跳转)的动画。为此,我将每个字母都放在 a 中<tspan>并在其上添加动画,无论如何变换都不起作用。

<!DOCTYPE html>
<html>
<head>
	<title>Test</title>
</head>

<style type="text/css">
svg text tspan {
	fill: #666;
	animation:jump 5s linear;
}

@keyframes jump {
	100% {
		fill: red;
		transform: translateY(40px);
	}
}
</style>

<body>

	<svg overflow="visible">
		<text font-size="20px" x="0" y="21"><tspan>t</tspan><tspan>e</tspan><tspan >s</tspan><tspan >t</tspan></text>
    	<text font-size="20px" x="0" y="42"><tspan>2 </tspan><tspan>l</tspan><tspan>i</tspan><tspan>g</tspan><tspan>n</tspan><tspan>e</tspan></text>
	</svg>

</body>
</html>

标签: htmlcssanimationsvg

解决方案


这通过 SMIL 为每个字母设置动画。这有点重复,因为 SMIL 动画仅适用于单个目标。

我们还必须避免在错误的地方使用空格,否则文本元素会假设我们实际上想要显示它而不是为了整洁而使用它。

<svg>
  <text y="50 50 50 50">
    <tspan>T<animate
         attributeName="dy" from="0" to="-40"
         dur="5s" begin="mouseover" restart="whenNotActive" /><set
         attributeName="fill" to="red"
         dur="5s" begin="mouseover" restart="whenNotActive" /></tspan><tspan>e<animate
         attributeName="dy" from="0" to="-40"
         dur="5s" begin="mouseover" restart="whenNotActive" /><set
         attributeName="fill" to="red"
         dur="5s" begin="mouseover" restart="whenNotActive" /></tspan><tspan>s<animate
         attributeName="dy" from="0" to="-40"
         dur="5s" begin="mouseover" restart="whenNotActive" /><set
         attributeName="fill" to="red"
         dur="5s" begin="mouseover" restart="whenNotActive" /></tspan><tspan>t<animate
         attributeName="dy" from="0" to="-40"
         dur="5s" begin="mouseover" restart="whenNotActive" /><set
         attributeName="fill" to="red"
         dur="5s" begin="mouseover" restart="whenNotActive" /></tspan></text>
</svg>


推荐阅读