使用 <use> 标签和 href 或 xlink:href 属性显示外部 SVG?

新手上路,请多包涵

<use> 元素加载时,SVG 显示不正确。我在它后面添加了一个 <img> 元素来说明预期结果:

 <svg>
  <use xlink:href="file.svg" href="file.svg"></use>
</svg>
<img src="file.svg" />

当前输出:

电流输出

工作小提琴: 演示

感谢任何能指出我错误的人。

原文由 seb 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 6.3k
2 个回答
  1. 你有这个错误: 不安全的尝试加载 URL https:…..svg from frame with URL https://…… Domains, protocols and ports must match

  2. 您需要使用您要使用的 svg 对象的 id

   <svg viewBox="0 0 14 16" width="50">
    <use xlink:href="sof.svg#id" fill="red"/>
  </svg>

请看这个例子: https ://codepen.io/enxaneta/project/editor/91143c063e6b9abf1b5c43a14a9937ea

原文由 enxaneta 发布,翻译遵循 CC BY-SA 4.0 许可协议

<use> 元素确实 复制 了您从 href 属性链接到的元素。你不能直接指向一个 file.svg ,你需要指向一个元素的 id

 <use xlink:href="path/to-the-file.svg#the-element"/>

 // since we can't store file in StackSnippets we'll download it first
fetch('https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg')
.then(r => r.blob())
.then(b =>
  // and create a blobURI, with the id of a <g> Element
  use.setAttributeNS(
    'http://www.w3.org/1999/xlink', 'href',
    URL.createObjectURL(b) + '#g4'
  )
);
 <svg width="200" height="200" viewBox="0 0 900 900">
  <use id="use"/>
</svg>

但请注意, 元素也可以直接显示您的图像(即使您将失去您可能从 获得的小控制:

 <svg width="200" height="200" viewBox="0 0 200 200">
  <image width="200" height="200" xlink:href="https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg"/>
</svg>

原文由 Kaiido 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题