2010-03-30 78 views
24

我已經dynamacally添加到iFrame中顯示的svg的圓形元素。 Chrome沒有顯示新的元素,還沒有嘗試FF。我需要調用一些重新刷新/刷新嗎?第一個圓實際上在svg文件中,其餘的來自腳本。如何讓Chrome重新繪製SVG動態添加的內容?

<iframe id="svgFrame" src="xmlfile1.svg" width="300" height="300"> 
<svg xmlns="http://www.w3.org/2000/svg" id="SVG1" width="200" height="200"> 
    <circle cx="20" cy="20" r="5"/> 
    <circle cx="165" cy="80" r="32"/> 
    <circle cx="15" cy="38" r="32"/> 
    <circle cx="140" cy="39" r="30"/> 
    <circle cx="178" cy="32" r="22"/> 
    ...etc 
    <circle cx="166" cy="130" r="16"/> 
</svg> 
</iframe> 

它創建的元素的javascript:

function RandomNumber(min, max) { 
    var r; 
    r = Math.floor(Math.random() * (max - min + 1)) + min; 
    return r; 
} 

var svg = document.getElementById("svgFrame").contentDocument; 

for (var i = 0; i < 99; i++) { 

    var n = svg.createElement("circle"); 
    n.setAttribute("cx" , RandomNumber(0 , 200)); 
    n.setAttribute("cy" , RandomNumber(0, 200)); 
    n.setAttribute("r" , RandomNumber(5, 35)); 

    svg.documentElement.appendChild(n); 
} 

回答

19

我還沒有嘗試過,你在做什麼,你實際上有兩個來源,但我知道Chrome瀏覽器不需要刷新/重繪時動態添加內容。

這是我的代碼,也許這會幫助你。

xmlns = "http://www.w3.org/2000/svg"; 
var C = document.createElementNS(xmlns,"circle"); 
C.setAttributeNS(null, "cx", cx); 
C.setAttributeNS(null, "cy", cy); 
C.setAttributeNS(null, "r", rad); 
document.getElementById("background").appendChild(C); 

哪裏背景只是一組(G標籤)

+0

我已將它添加到問題中。 – Adrian 2010-03-30 12:43:45

+0

爲什麼使用「.contentDocument」? – Shaunwithanau 2010-03-30 13:21:33

+0

僅用於.contentDocument,因爲是我發現的第一個具有createElement方法的道具 - 從此以後就有了getSVGDocument方法......是否使用了更正確的方法? – Adrian 2010-03-30 13:33:56

13

我猜的ID,但你嘗試過createElementNS("http://www.w3.org/2000/svg","circle"),而不是createElement("circle")

+0

我會試試它,但用Inspect Element查詢文檔似乎顯示正確的名稱空間。畢竟所有的createElement被一個具有正確命名空間的對象調用... – Adrian 2010-03-30 13:07:49

+0

剛剛嘗試過它,它知道的作品 - 當我來到名稱空間時,必須讀取檢查器錯誤..... – Adrian 2010-03-30 13:35:00

+0

也只是看DOM在Inpector中,我一直認爲添加元素作爲svg的子元素,他們將具有與svg相同的名稱空間... – Adrian 2010-03-30 13:38:30