2012-12-03 207 views
1

我正在使用html5,js & css3。無法訪問svg路徑屬性

我有以下代碼:

HTML

<object id="bottom" data="img/model/skirt.svg" 
title="bottom" type="image/svg+xml" width="325" 
height="500"> </object> 

JS

var b = document.getElementById("bottom"); 
b = b.getSVGDocument().getElementById("here"); 
alert(b); 

,這給了我 「對象SVGPathElement」。

但是,當我嘗試訪問填充屬性,我得到一個「未定義」的消息。例如, alert(b.fill);

fill屬性肯定是在svg文件中設置的。我明顯錯過了一些東西。任何指針讚賞。

+0

你怎麼知道那個特定元素的填充屬性設置? –

+0

我在所討論的路徑元素上設置了id =「here」,它在該svg文件中是唯一的id,在該路徑元素中填充=「#666666」。這是一個很好的問題,但我徹底檢查了它:-) –

回答

4

必須使用svgEl.setAttribute(name, value)svgEl.getAttribute(name)訪問SVG屬性。

沒有訪問HTMLElement等屬性的捷徑。

但如果你真的願意,你可以擴展SVGElement.prototype

Object.defineProperties(SVGElement.prototype, { 
    fill: { 
    get: function() { 
     return this.getAttribute('fill'); 
    }, 
    set: function(value) { 
     return this.setAttribute('fill', value); 
    } 
    } 
}); 
+0

:-) spot on,that works。謝謝。 –

+3

對於屬性(如'fill'),也可以使用CSS OM,例如'elm.style.fill'(如果填充是內聯樣式)或'window.getComputedStyle' - 請參見http:// www。 w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle。 –

+0

@ErikDahlström很好的電話。 – xiaoyi