获取SVG< image>的“xlink:href”属性元素在HTML DOM中动态地使用JS [英] Getting 'xlink:href' attribute of the SVG <image> element dynamically using JS in HTML DOM

查看:2210
本文介绍了获取SVG< image>的“xlink:href”属性元素在HTML DOM中动态地使用JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个建设:

<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> 元素:

I want to get pic.jpg url and I need to begin from the most outer div, not exactly from the source <image> element:

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

我的问题是什么是正确的方法来获得这样的因为在我试图这样做之前,它也可以在Chrome中运行正常(我没有尝试其他浏览器):

My question is what is the right way to get such kind of attributes from element like SVG and its children?

/ p>

Because before I tried to do this way and it also worked fine in Chrome (I didn't try other browsers):

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 ()我得到空白的结果:

But when I tried to use getAttributeNS() I got blank result:

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');

这篇关于获取SVG&lt; image&gt;的“xlink:href”属性元素在HTML DOM中动态地使用JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆