2012-04-21 29 views
12

我想通過jQuery在SVG中添加項目。 我可以很好地插入標籤,如<rect /><text />,但我無法插入帶有標籤<image />的圖像。無法通過jQuery在SVG中添加圖像:<image />標記變爲<img />

這個標籤成爲<img />自動,它不能顯示SVG圖像: ​​

我如何避免這種情況? 如果這是不可能的,是否有另一種方法使用JavaScript/jQuery插入圖像到SVG中。

+1

嘗試使用我的jQuery的破解[http://stackoverflow.com/questions/11792754/create-and-access-svg-tag-with-jquery/14985470# 14985470] [1] [1]:http://stackoverflow.com/questions/11792754/create-and-access-svg-tag-with-jquery/14985470#14985470 – 2013-02-20 21:29:58

回答

16

你應該使用createElementNS()

var img = document.createElementNS('http://www.w3.org/2000/svg','image'); 
img.setAttributeNS(null,'height','536'); 
img.setAttributeNS(null,'width','536'); 
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg'); 
img.setAttributeNS(null,'x','10'); 
img.setAttributeNS(null,'y','10'); 
img.setAttributeNS(null, 'visibility', 'visible'); 
$('svg').append(img); 
2

jQuery本身無法正確處理SVG操作,as this answer explains。您應該使用Raphael,或者上面鏈接中描述的其中一種黑客方法。