【问题标题】:SVG CSS transition not working on `use` element (Chrome)SVG CSS过渡不适用于`use`元素(Chrome)
【发布时间】:2020-11-08 03:53:59
【问题描述】:

我无法让 CSS 过渡来处理 SVG 内的 use 元素。

它适用于原始 SVG,但在我使用 use 时不起作用。见下文。

这似乎是特定于 Chrome 的(两个示例都适用于 FF)。

.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 中工作。
  • 在 Firefox 上对我来说似乎可以正常工作。在您使用的任何浏览器的错误跟踪器上将其报告为错误。
  • 介意启动 Chrome 并告诉我它是否有效吗?我可以确认这个示例在 FF 中确实有效,尽管我的实际用例没有。我会进一步调查,看看我是否可以在 FF 中复制中断。
  • 让它在 FF 中也能正常工作。我会提交一个错误。谢谢。
  • @enxaneta 感谢您的解决方法。如果您提交答案,我会接受。

标签: css google-chrome svg css-transitions


【解决方案1】:

正如其他人所指出的,这似乎是 Chrome 中的一个错误。解决方法见下文。

正如我所评论的:您可以将样式应用于 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>

【讨论】:

  • 您还可以在 CSS 中设置 use 标签的样式。例如:.stretched-rect use { fill: red; transition: 1s fill; }
  • 这个错误和解决方法破坏了我现有的程序,该程序使用 use 语句引用另一个带路径的内联 svg。带有路径的内联 svg 具有由动画等动态更改的类。知道何时修复此错误!
猜你喜欢
  • 1970-01-01
  • 2016-02-13
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
相关资源
最近更新 更多