如何获取svg符号以引用外部文件中的另一个符号



我试图在外部文件的符号中引用一个符号,但无法在Chrome或Firefox中使用。

我可以在另一个符号中引用一个符号,如果它们是在html文件的顶部定义的,这没有问题:

<!-- in the html file -->
<svg width="0" height="0">
  <symbol id="local-circle" viewBox="0 0 100 100" overflow="visible">
    <circle
      cx="50"
      cy="50"
      r="50"
      fill="red"
    />
  </symbol>
  <symbol id="local-sym" viewBox="0 0 100 100" overflow="visible">
    <rect
      x="0"
      y="0"
      width="100"
      height="100"
      fill="blue"
    />
    <use
      xlink:href="#local-circle"
      x="0"
      y="0"
      width="100"
      height="100"
    />
  </symbol>
</svg>

但是,当我尝试将此代码放入外部文件时,符号中的符号不会显示出来。

<!-- in an external file called test.svg -->
<svg xmlns="http://www.w3.org/2000/svg">
  <!-- This shows up fine in the html file -->
  <symbol id="ext-circle" viewBox="0 0 100 100" overflow="visible">
    <circle
      cx="50"
      cy="50"
      r="50"
      fill="red"
    />
  </symbol>
  <!-- But here, the rect shows up, but not the referenced circle -->
  <symbol id="ext-sym" viewBox="0 0 100 100" overflow="visible">
    <rect
      x="0"
      y="0"
      width="100"
      height="100"
      fill="blue"
    />
    <use
      xlink:href="#ext-circle"
      x="0"
      y="0"
      width="100"
      height="100"
    />
  </symbol>
</svg>

我甚至尝试了一种文件内符号引用外部符号的组合,但没有成功:

<!-- in the html file -->
<svg width="0" height="0">
  <symbol id="combo-sym" viewBox="0 0 100 100" overflow="visible">
    <rect
      x="0"
      y="0"
      width="100"
      height="100"
      fill="blue"
    />
    <use
      xlink:href="test.svg#ext-circle"
      x="0"
      y="0"
      width="100"
      height="100"
    />
  </symbol>
</svg>

知道我该怎么做吗?我会有很多符号,我不想在html文件中定义它们。

外部svg无效,因为它缺少xlink命名空间定义,即xmlns:xlink="http://www.w3.org/1999/xlink".一旦我修复了这个圆圈在Firefox中显示良好的问题。

<svg>
    <use
      xlink:href="test.svg#ext-sym"
      x="0"
      y="0"
      width="100"
      height="100"
    />
</svg>

最新更新