我有一个结构:
<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
url ,我需要从最外层的 div 开始,而不是完全从源 <image>
开始元素:
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 及其子元素等元素获取此类属性的正确方法是什么?
因为在我尝试这样做之前,它在 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
最佳答案
正确的用法是getAttributeNS('http://www.w3.org/1999/xlink', 'href');
关于dom - 在 HTML DOM 中使用 JS 动态获取 SVG <image> 元素的 'xlink:href' 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12422668/