2014-05-23 24 views
1

我在我的代碼中有兩個猴子:第一個是靜態的(用SVG標籤寫的),沒關係,但第二個(用JS生成)不可見儘管兩個標籤的代碼在運行後都非常相似。這怎麼可能?我該如何解決它?<image>在SVG中:靜態圖像是可見的,但動態不是

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

    <image xlink:href="http://6962mnpm.blox.pl/resource/118392wtf.jpg" 
    height="250px" width="250px" x="100px"></image> 

</svg> 

<script> 
    var test = document.createElementNS("http://www.w3.org/2000/svg", "image"); 
    test.setAttribute("xlink:href", 
     "http://6962mnpm.blox.pl/resource/118392wtf.jpg"); 
    test.setAttribute("height", "250px"); 
    test.setAttribute("width", "250px"); 
    test.setAttribute("x", "400px"); 
    document.querySelector("svg").appendChild(test); 
</script> 

回答

3

不能使用setAttribute添加一個命名空間屬性,即使它看起來正確的檢查員。請使用setAttributeNS,如下所示:

setAttributeNS('http://www.w3.org/1999/xlink','href','http://6962mnpm.blox.pl/resource/118392wtf.jpg'); 

現在猴子應該正確渲染。

var SVGDaddy = "http://www.w3.org/2000/svg"; 
var TESTOBRAZKA = document.createElementNS(SVGDaddy, "image"); 
with(TESTOBRAZKA) { 
    setAttributeNS('http://www.w3.org/1999/xlink','href','http://6962mnpm.blox.pl/resource/118392wtf.jpg'); 
    setAttribute("height", "250px"); 
    setAttribute("width", "250px"); 
    setAttribute("x", "100px"); 
} 
document.querySelector("svg").appendChild(TESTOBRAZKA); 

演示:http://jsfiddle.net/Palpatim/kGy5d/

1

href屬性有xlink命名空間,所以你不能只用setAttribute()。你必須使用setAttibuteNS()。試試這個:

setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", 
       "http://6962mnpm.blox.pl/resource/118392wtf.jpg"); 
相關問題