簡體   English   中英

在Javascript中將foreignObject附加到SVG

[英]Append a foreignObject to a SVG in Javascript

我有一個id為“graphe”的SVG元素。 我想在這個元素后附加一個包含段落的foreignObject。 我讀到有必要在這個對象中有一個“主體”(這是真的嗎?)。 在所有情況下,這段代碼都不起作用:

foreign = document.createElementNS('http://www.w3.org/2000/svg', "foreignObject");
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'x', 250);
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'y', 100);
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'width', 500);
foreign.setAttributeNS('http://www.w3.org/2000/svg', 'height', 150);

body = document.createElement("body");
body.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');

texte = document.createElement("p");
texte.textContent = "EXAMPLE";

foreign.appendChild(body);
body.appendChild(texte);
document.getElementById("graphe").appendChild(foreign);

我不明白為什么。 當我在Chrome中打開DOM Inspector時,我可以看到所有內容都在這里。 但沒有顯示任何內容。 當我直接在源中重新復制DOM Inspector的對象代碼時,我在頁面上看到了我的對象。

[編輯] JSFiddle演示: http//jsfiddle.net/uwZja/

永遠不要在svg中使用svg名稱空間作為屬性。

更改:

foreign.setAttributeNS('http://www.w3.org/2000/svg', ...

至:

foreign.setAttributeNS(null, ...

或者:

foreign.setAttribute("x", ...

此外部分:

body.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');

除非你想將文檔序列化為字符串,否則它是無用的。 它沒有效果,在調用createElement/createElementNS時會決定創建的元素類型。 它沒有改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM