dom - 在 HTML DOM 中使用 JS 动态获取 SVG <image> 元素的 'xlink:href' 属性

标签 dom svg xlink

我有一个结构:

<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/

相关文章:

SVG 主导基线在 Safari 中不起作用

javascript - 嵌入的 svg 何时实际加载,我如何检查它是否加载

svg - 内联 svg 不显示在 xhtml 中

html - SVG 使用元素引用外部文件在 Safari 中不起作用

javascript - 解析 &lt;script&gt; 和/或 <noscript> 标签中找到的 <img> src 属性

javascript - 为什么 xpath 较慢

javascript - Javascript 中的突变事件不起作用

javascript - 在两个 HTML 文件之间交换正文标签

javascript - React 中的 SVG 操作

javascript - 是否可以使用 HTML 的 .querySelector() 通过 SVG 中的 xlink 属性进行选择?