9
動態使用JS的SVG 元素的屬性我有一個結構:走走的XLink:HREF「在HTML DOM
<div id="div">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg">
<image x="2cm" y="2cm" width="5cm" height="5cm" id="img" xlink:href="pic.jpg"></image>
</svg>
</div>
我想pic.jpg
網址,我需要從最外層div開始,
var div = document.getElementById("div");
var svg = div.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];
var img = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')[0];
var url = img.getAttribute('xlink:href'); // Please pay attention I do not use getAttributeNS(), just usual getAttribute()
alert(url); // pic.jpg, works fine
我的問題是什麼是能得到這樣一種像SVG和它的孩子從元素屬性的正確方法:從源<image>
元素不完全?
因爲之前我試圖做這樣的方式,它在Chrome中也能正常工作(我沒有嘗試其他瀏覽器):
var svg = div.getElementsByTagName('svg')[0]; // I do not use NS
var img = svg.getElementsByTagName('image')[0];
var url = img.getAttribute('xlink:href'); // and do not use getAttributeNS() here too
alert(url); // pic.jpg, works fine
但是當我試圖用getAttributeNS()
我得到空白結果:
var svg = div.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];
var img = svg.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'image')[0];
// Please pay attention I do use getAttributeNS()
var url = img.getAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href');
alert(url); // but I got black result, empty alert window
謝謝!這個答案幫助我*通過JavaScript在我的SVG內容中設置圖像的xlink:href屬性。我的代碼如下所示:img.setAttributeNS('http://www.w3.org/1999/xlink','href','new.url');其中new.url是我想要替換原始圖片的網址。 – grw
現在如何用jQuery選擇器做同樣的事情? –
在SVG中使用jquery會引起很大的痛苦,最好避免。 –