SVG CSS过渡在`use`元素上无法工作(Chrome)

4

我无法使CSS过渡效果在SVG中的use元素上生效。

在原始SVG上可以正常工作,但在使用use后不行。请参见下面代码。

这似乎是Chrome特有的问题(两个示例都可以在Firefox中工作)。

.stretched-rect {
  width: 50px;
  height: 50px;
}
.stretched-rect svg {
  width: 100%;
  height: 100%;
}

.stretched-rect {
  --fill-color: red;
}
.stretched-rect:hover {
  --fill-color: blue;
}
  Example with original svg (this works):
  <div class="stretched-rect">
    <svg viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" style="fill: var(--fill-color); transition: 1s fill;"/>
    </svg>
  </div>
  
  <br><br>
  <!-- Define SVG, so we can use it with `use` -->
  <svg style="display: none;">
    <symbol id="svg-rect" viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" style="fill: var(--fill-color); transition: 1s fill;"/>
    </symbol>
  </svg>
  
  Example using "use" (this does not work):
  <div class="stretched-rect">
    <svg><use xlink:href="#svg-rect"/></svg>
  </div>


在 Mozilla 中可用。 - VXp
在Firefox上我用起来没问题。如果你使用的浏览器有问题,可以在bugtracker上报告它。 - Robert Longson
能否打开Chrome并告诉我它是否可用?我可以确认这个例子在FF中是有效的,但我的实际用例不是。我会进一步调查并看看是否可以在FF中复制错误。 - JS_Riddler
1
@enxaneta,感谢您提供的解决方法。如果您提交答案,我会接受的。 - JS_Riddler
我没有答案,因为这是一个“bug”,但这是一个很酷的问题,非常具体化了 :) - Sheraff
显示剩余2条评论
1个回答

2

正如其他人所指出的那样,这似乎是Chrome浏览器中的一个bug。请参见下面的解决方法。

正如我所评论的:不要在symbol中为rect设置样式,而应将样式应用于use元素: 删除symbol的rect样式,并将其粘贴到use元素中:

.stretched-rect {
  width: 50px;
  height: 50px;
}
.stretched-rect svg {
  width: 100%;
  height: 100%;
}

.stretched-rect {
  --fill-color: red;
}
.stretched-rect:hover {
  --fill-color: blue;
}
Example with original svg (this works):
  <div class="stretched-rect">
    <svg viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" style="fill: var(--fill-color); transition: 1s fill;"/>
    </svg>
  </div>
  
  <br><br>
  <!-- Define SVG, so we can use it with `use` -->
  <svg style="display: none;">
    <symbol id="svg-rect" viewbox="0 0 100 100" preserveAspectRatio="none">
      <rect width="100" height="100" rx="15" />
    </symbol>
  </svg>
  
  Example using "use" (this is working now):
  <div class="stretched-rect">
    <svg><use xlink:href="#svg-rect" style="fill: var(--fill-color); transition: 1s fill;"/></svg>
  </div>


1
您也可以在CSS中为use标签设置样式。例如:.stretched-rect use { fill: red; transition: 1s fill; } - JS_Riddler
这个 bug 和解决方法破坏了我现有的程序,该程序使用 use 语句引用另一个带有路径的内联 SVG。该内联 SVG 具有通过动画等动态更改的类。不知道这个 bug 何时会被修复! - tlarson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接