[英]Read Attributes of SVG-Elements in HTML via JS
我有以下标记(HTML与本机SVG):
<!doctype html>
<!-- ...
html-Elements
... -->
<svg version="1.1" ... >
<defs> <circle id="infop" cx="0" cy="0" r="9" /> </defs>
<!-- ...
svg Elements
... -->
<svg> <!-- to have separate coordinate-system -->
<g id="outSvg"></g>
</svg>
...
js方法输出一行和几个<use href="infotop">
Elements到#outSvg
(成为图形)。 <use>
元素具有onmouseover-Events以显示工具提示。
现在,当涉及到检索<use>
的onmouseover-function
中的坐标时,我会遇到问题:
我尝试了以下不同的方法来检索值:
function showInfo(evt){
console.log("target: "+evt.target);
console.log("AttrNS: "+evt.target.getAttributeNS(null,"x"));
console.log("Attrib: "+evt.target.getAttribute("x"));
console.log("basVal: "+evt.target.x.baseVal.value);
console.log("corrEl: "+evt.target.correspondingUseElement.x.baseVal.value);
产生以下输出:
//target -> ** [object SVGUseElement] in FF, in all other browsers: [object SVGElementInstance])
//AttrNS -> Works only in FF
// * Uncaught TypeError: Object #<SVGElementInstance> has no method 'getAttributeNS'
//Attrib -> Works only in FF
// * Uncaught TypeError: Object #<SVGElementInstance> has no method 'getAttribute'
//basVal -> works only in FF
// * Uncaught TypeError: Cannot read property 'baseVal' of undefined
//corrEl -> fails in FF but works in Ch, O and IE
浏览器:FF10,Ch16,O11.61,IE9
题:
为什么getAttribute()
在其他浏览器中失败? 我错过了重要的事吗? 是否有一致的方法来检索值crossbrowser ? (除了通过evt.target.x
和evt.target.correspondingUseElement.x
之间的切换)
重要的是:只有香草js,我知道浏览器开关,这不是重点! 一旦找到时间,我会在需要时提供小提琴。 最后 - 谢谢你阅读本文!
编辑:*添加了js-errors
EDIT2:** FF返回另一个对象而不是其他浏览器
好吧,在阅读了ErikDahlströms的回答之后,我发现FF表现不对。 它应该直接返回Element-Instance而不是Use-Element。
我现在使用以下代码:
var el = (evt.target.correspondingUseElement)?evt.target.correspondingUseElement:evt.target;
console.log(el.getAttribute("x"));
这样我就可以在所有浏览器中通过getAttribute()
一致地检索属性。
你能试试吗? evt.target.getAttributeNode("x").nodeValue
。 我试过这个在safari,chrome,Firefox中工作正常。
据我所知,Firefox不支持SVGElementInstance。
以下是来自w3c SVG 1.1 Second Edition测试套件的SVGElementInstance的几个测试,以验证:
你应该做的是提供一个后备解决方案,如果没有SVGElementInstance,这很容易检测,例如:
if (elm.correspondingUseElement) {
/* elm is a used instance, not a real element */
} else {
/* fallback solution */
}
如果元素是SVGElementInstance,它将具有correspondingUseElement
的UserElement属性,否则它将不具有它。 普通的svg元素不会有这个属性,只有用过的实例才会拥有它。
你试过evt.target.getAttributeNS(evt.target.parent.namespaceURI,"x")
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.