【问题标题】:Getting 'xlink:href' attribute of the SVG <image> element dynamically using JS in HTML DOM在 HTML DOM 中使用 JS 动态获取 SVG <image> 元素的“xlink:href”属性
【发布时间】:2012-09-07 12:13:35
【问题描述】:

我有一个结构:

<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开始,而不是完全从源&lt;image&gt;元素开始:

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

【问题讨论】:

    标签: dom svg xlink


    【解决方案1】:

    正确用法是getAttributeNS('http://www.w3.org/1999/xlink', 'href');

    【讨论】:

    • 谢谢!这个答案帮助我通过 JavaScript 在我的 SVG 内容中设置图像的 xlink:href 属性。我的代码如下: img.setAttributeNS('w3.org/1999/xlink', 'href', 'new.url');其中 new.url 是我要替换原始图像的 url。
    • 将 jquery 与 SVG 一起使用会给您带来很大的痛苦,最好避免。
    猜你喜欢
    • 2014-02-07
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    相关资源
    最近更新 更多