2017-01-23 56 views
1

我有以下簡單的例子。它存儲在image.svg爲什麼SVG中的<use>標籤不起作用?

<svg> 
 
     <defs> 
 
     <g id="shape"> 
 
      <circle cx="100" cy="100" r="100" /> 
 
     </g> 
 
     </defs> 
 
</svg>

但是,把這個代碼的HTML文件不會加載任何東西。這是爲什麼?

<svg> 
     <use xlink:href="#shape" x="10" y="10" /> 
</svg> 

我在做什麼錯?我似乎無法使其工作。

+0

堆棧片段彼此隔離(以便在一個文檔中的ID不會與其他文檔的ID衝突)。一般來說,這應該是可能的。 –

回答

3

你需要與你想使用的形狀SVG內使用標籤:

<svg> 
    <defs> 
     <g id="shape"> 
      <circle cx="100" cy="100" r="100" /> 
     </g> 
    </defs> 

    <use xlink:href="#shape" x="10" y="10" /> 
</svg> 
+0

你做了一個堆棧片段,但你一般不會。 –

+0

我認爲在同一個文檔中的兩個SVG也可以工作:https://jsfiddle.net/t31vgbaj/ – pawel

+0

這個問題非常意味着該定義是在另一個文件中,雖然... – lonesomeday

4

如果您正在使用的元素從另一個文件,你必須指定文件!

<use xlink:href="#shape" x="10" y="10" /> 

這意味着「使用當前文檔中的#shape元素」。

要從另一個文檔導入,你需要把參考SVG文件中xlink:href屬性:

<use xlink:href="image.svg#shape" x="10" y="10" /> 

顯然,你需要檢查的路徑是正確的在這裏。請注意,這在任何版本的Internet Explorer中都不受支持,儘管可以使用polyfills。

1

您需要的命名空間外部SVG文件......我已經添加填充來呈現圓形,否則這將是透明的:

<svg xmlns="http://www.w3.org/2000/svg" > 
 
    <symbol id="shape" width="200" height="200" viewbox="0 0 200 200"> 
 
    <circle cx="100" cy="100" r="100" fill="currentColor" /> 
 
    </symbol> 
 
    <text y="20">Symbol above will not render unless referenced by use element</text> 
 
</svg>

然後當你引用它,你需要使用正確的命名空間的XLink:

svg.defs-only { 
 
    display:block; position: absolute; 
 
    height:0; width:0; margin: 0; padding: 0; 
 
    border: none; overflow: hidden; 
 
} 
 

 
svg { 
 
    color: orange; 
 
    stroke: red; 
 
} 
 

 
.purple { 
 
    color: purple; 
 
    stroke: black; 
 
}
<svg class="defs-only" xmlns="http://www.w3.org/2000/svg" > 
 
    <symbol id="shape" width="50" height="50" viewbox="0 0 50 50"> 
 
    <circle cx="25" cy="25" r="20" fill="currentColor" stroke="inherit" /> 
 
    </symbol> 
 
</svg> 
 

 
<svg xmlns:xlink="http://www.w3.org/1999/xlink"> 
 
    <use xlink:href="#shape" x="10" y="10" /> 
 
    <use xlink:href="#shape" x="80" y="10" class="purple" /> 
 
</svg>

如果您正在引用外部文件,則需要將文件名放在#image.svg#shape確保您獲得正確的路徑。

請注意,並非所有瀏覽器都支持片段標識符 - 特別是IE和Edge--您需要爲這些瀏覽器使用像svg4everybody一樣的javascript填充。

解決方法 - 使用SVG內聯只

相關問題