[英]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.