如何让SVG的<use>元素仅继承指定<animate>动画?
让
要实现id为rect2的<use>元素只继承<rect>的fill动画、不继承x动画,且不创建额外defs元素,有两种实用方法:
方法一:用CSS精准控制动画启用状态
给defs里的两个动画分别加上id,再通过CSS给rect2禁用不需要的x动画:
<svg xmlns="http://www.w3.org/2000/svg"> <style> /* 直接隐藏rect2继承的x动画 */ #rect2 #x-animation { display: none; } </style> <defs> <rect id="rectangle" fill="red" width="25" height="25"> <animate id="fill-animation" attributeName="fill" values="red;blue;green;red" dur="1s" repeatCount="indefinite" /> <animate id="x-animation" attributeName="x" values="0;50;0" dur="1s" repeatCount="indefinite" /> </rect> </defs> <!-- 保留两种动画 --> <use id="rect1" href="#rectangle" /> <!-- 仅继承fill动画 --> <use id="rect2" href="#rectangle" y="50" /> </svg>
这种方法直接从根源禁用不需要的动画,逻辑清晰,不会产生额外的动画冲突。
方法二:用覆盖动画抵消原动画效果
如果不想修改defs里的代码,可以直接在rect2上添加一个保持x属性不变的动画,抵消继承来的x动画:
<svg xmlns="http://www.w3.org/2000/svg"> <defs> <rect id="rectangle" fill="red" width="25" height="25"> <animate attributeName="fill" values="red;blue;green;red" dur="1s" repeatCount="indefinite" /> <animate attributeName="x" values="0;50;0" dur="1s" repeatCount="indefinite" /> </rect> </defs> <use id="rect1" href="#rectangle" /> <use id="rect2" href="#rectangle" y="50"> <!-- 覆盖x动画,让x始终保持0 --> <animate attributeName="x" values="0;0" dur="1s" repeatCount="indefinite" fill="freeze" /> </use> </svg>
这种方法无需改动原defs代码,适合无法修改原始SVG结构的场景。
内容的提问来源于stack exchange,提问作者Pedro Henrique
相关产品推荐
相关产品推荐

