我有以下标记(带有本机SVG的HTML):
<!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">元素输出到#outSvg (以成为一个图)。<use>元素有onmouseover事件来显示工具提示。
现在,在检索onmouseover-function <use> 的中的坐标时,遇到了一些问题:
我尝试了以下不同的方法来检索值:
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 10,Ch16,O11.61,IE9
问题:
为什么getAttribute()在其他浏览器中失败?我错过了什么重要的事情吗?是否有一致的方法来检索值crossbrowser?(除了通过evt.target.x和evt.target.correspondingUseElement.x之间的切换)
重要:只有香草js,而且我知道浏览器开关,这不是重点!如果需要的话,只要有时间,我就会提供一把小提琴。终于-谢谢你看这个!
编辑:*添加js-错误
EDIT2:** FF返回比其他浏览器更多的对象
发布于 2012-02-18 12:35:12
在阅读了Erik Dahlstr m的答案之后,我注意到FF的行为是错误的。它应该返回一个元素实例,而不是直接返回Use-元素。
我现在使用以下代码:
var el = (evt.target.correspondingUseElement)?evt.target.correspondingUseElement:evt.target;
console.log(el.getAttribute("x"));通过这种方式,我可以在所有浏览器中一致地通过getAttribute()检索属性。
发布于 2012-02-15 08:53:59
你能试试这个吗?evt.target.getAttributeNode("x").nodeValue。我在safari,chrome,Firefox上试了一下它的工作原理。
发布于 2012-02-15 21:07:22
据我所知,火狐不支持SVGElementInstance。
下面是来自SVGElementInstance SVG1.1第二版测试套件的几个w3c测试,以验证:
您应该做的是在SVGElementInstance不存在的情况下提供一个后备解决方案,这很容易检测,例如:
if (elm.correspondingUseElement) {
/* elm is a used instance, not a real element */
} else {
/* fallback solution */
}如果元素是一个SVGElementInstance,它将具有correspondingUseElement属性,否则它将不具有它。普通svg元素将不具有此属性,只有已使用的实例才有此属性。
https://stackoverflow.com/questions/9275695
复制相似问题