5

我有以下标记(带有原生 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-Events 来显示工具提示。

现在,在检索 i 中的坐标时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、Ch16、O11.61、IE9

问题:

为什么getAttribute()在其他浏览器中失败?我错过了什么重要的东西吗?是否有一致的方法来检索值crossbrowserevt.target.x(除了通过和之间的切换evt.target.correspondingUseElement.x

重要:只有香草js,我知道浏览器开关,那不是重点!如果需要,我会在找到时间后立即提供小提琴。最后——感谢您阅读本文!

编辑:* 添加了 js 错误

EDIT2:** FF 返回另一个对象而不是其他浏览器

4

4 回答 4

7

好吧,在阅读了 Erik Dahlströms 的回答后,我注意到 FF 的行为是错误的。它应该直接返回一个元素实例而不是使用元素。

我现在使用以下代码:

var el = (evt.target.correspondingUseElement)?evt.target.correspondingUseElement:evt.target;

console.log(el.getAttribute("x"));

这样我就可以getAttribute()在所有浏览器中一致地检索属性。

于 2012-02-18T12:35:12.497 回答
2

据我所知,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属性,否则将没有它。普通的 svg 元素不会有这个属性,只有使用过的实例才会有它。

于 2012-02-15T21:07:22.593 回答
2

你能试试这个吗?evt.target.getAttributeNode("x").nodeValue. 我在 safari、chrome、Firefox 中试过这个,它工作正常。

于 2012-02-15T08:53:59.160 回答
0

你试过了evt.target.getAttributeNS(evt.target.parent.namespaceURI,"x")吗?

于 2012-02-14T11:58:31.413 回答