2017-02-08 27 views
0

在我的Chrome擴展中,我嘗試顯示SVG精靈,但它沒有顯示內容。我沒有看到控制檯中的任何錯誤,並嘗試本地和在線。我也嘗試使用IMG標籤無濟於事。我發現的所有其他建議都是關於構造形狀的。在Chrome擴展中動態添加SVG精靈

var svg = div.appendChild(document.createElement("svg")); 
    svg .classList.add("actionButtonImage"); 
var use = svg.appendChild(document.createElement("use")); 
    use .setAttribute("xmlns:xlink"," http://www.w3.org/1999/xlink"); 
    use .setAttribute("xlink:href", href); 

編輯:我不是在尋找使在頁面中的載體,我使用外部SVG精靈!並花了一天半的時間研究這個!


到目前爲止,我有這個無濟於事

var svg = div.appendChild(document.createElementNS("http://www.w3.org/2000/svg", "svg")); 
    svg .classList.add("actionButtonImage"); 
var use = svg.appendChild(document.createElementNS("http://www.w3.org/1999/xlink", "use" )); 
    use .setAttributeNS("http://www.w3.org/1999/xlink","href",href); 
+0

你可以創建一個img標籤並引用src作爲svg源代碼。您還需要將其附加到擴展 – andrew196

+1

[在HTML中使用javascript動態創建SVG元素]的可能的副本(http://stackoverflow.com/questions/20539196/creating-svg-elements-dynamically-with-javascript-inside -html) – Makyen

+1

使用不是xlink命名空間中的元素,它位於svg命名空間中。它的href屬性在xlink命名空間中(儘管你有這個位)。 –

回答

2

您不能創建的createElement SVG元素,你需要createElementNS並提供SVG namespace

同樣,您不能使用setAttribute在xlink命名空間中設置屬性,您只能在null命名空間中創建屬性。您需要使用setAttributeNS在xlink命名空間中設置屬性。

最後xmlns:xlink不是一個真正的屬性,它是由serialisers創建的,作爲名稱空間中正確創建的屬性和元素的副作用,因此您不需要使用setAttribute來創建它。

+0

你的回答已經證明有幫助,謝謝! –