2014-09-20 80 views
5

我有我的文檔中的SVG和我添加了一個符號,以它使用JavaScript這樣的:爲什麼SVG使用javascript創建的元素沒有顯示?

var myScene =document.getElementById('myScene'); 
var useSVG = document.createElement('use'); 
useSVG.setAttribute('xlink:href','spriteSheet.svg#mySymbol'); 
useSVG.setAttribute('x','10'); 
useSVG.setAttribute('y','30'); 
useSVG.setAttribute('width','10'); 
useSVG.setAttribute('height','10'); 
myScene.appendChild(useSVG); 

符號不顯示,而生成的代碼是完全一樣寫在HTML至極另一個節點是正確顯示。調試器顯示

代碼:

<svg id="myScene" width="200px" height="200px"> 
    <use xlink:href="spriteSheet.svg#mySymbol" x="5" y="50" width="10" height="10"></use> 
    <!-- this one was in html, it is visible --> 
    <use xlink:href="spriteSheet.svg#mySymbol" x="10" y="30" width="10" height="10"></use> 
    <!-- this one is added with javascript. it is not displayed --> 
</svg> 
+1

下面的答案是遠遠不夠的,但指向正確的方向。在這裏你還必須使用'document.createElementNS'而不是'document.createElement'來創建'use'元素。這[回答](http://stackoverflow.com/questions/16488884/add-svg-element-to-existing-svg-using-dom)解決了類似的問題。 – 2014-09-20 10:41:17

+0

我試過了所有的東西,我無法讓它工作。無法找到工作示例。我的解決方案是給硬編碼的USE標記一個ID,並用node.cloneNode()複製它。仍在尋找一個工作的例子。 – bokan 2014-09-20 12:23:04

回答

8

您需要使用createElementNS()來創建SVG元素。基本的createElement()在HTML命名空間中創建元素。所以你基本上已經創建了<html:use>元素而不是<svg:use>

var myScene =document.getElementById('myScene'); 
var useSVG = document.createElementNS('http://www.w3.org/2000/svg', 'use'); 
useSVG.setAttributeNS('http://www.w3.org/1999/xlink','href','spriteSheet.svg#mySymbol'); 
useSVG.setAttribute('x','10'); 
useSVG.setAttribute('y','30'); 
useSVG.setAttribute('width','10'); 
useSVG.setAttribute('height','10'); 
myScene.appendChild(useSVG); 

Demo here

更新

我剛剛意識到有一個與你的代碼中的第二個問題。您在href中使用外部參考(它引用另一個文件中的符號)。看來IE不支持外部引用。

我發現了更多的信息,以及可能的解決方法,在這裏:http://css-tricks.com/svg-use-external-source/

+0

謝謝...但它適用於Chrome和Firefox,但不適用於IE 10.您有想法爲什麼嗎? – bokan 2014-09-20 14:35:13

+0

您可能需要執行'useSVG.setAttributeNS('http://www.w3.org/1999/xlink','xlink:href','spriteSheet.svg#mySymbol') ;'在IE上試試,如果仍然不行,請發佈一個jsfiddle,這樣我們就可以看到你的代碼 – 2014-09-20 20:00:09

+0

仍然無效,也許是因爲我使用了SVG符號, – bokan 2014-09-21 10:57:40

1

我不知道到100%,但我認爲你需要設置使用setAttributeNS()這樣的xlink:href屬性:

useSVG.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'spriteSheet.svg#mySymbol'); 

同時確保了名稱空間在您的文檔中聲明。

<html xmlns:xlink="http://www.w3.org/1999/xlink"> 

<!-- or if standalone svg --> 

<svg xmlns:xlink="http://www.w3.org/1999/xlink"> 

但是,這樣一來我解決同一問題的XHTML文檔中,可能會爲HTML5或獨立SVG工作,太。

xlink specification

好運!

+1

剛剛試過它,它不工作;(謝謝你無論如何。 它確實寫入href屬性沒有Xlink的'Xlink':href。 – bokan 2014-09-20 09:22:31