通过 JS 读取 HTML 中 SVG 元素的属性

问题描述 投票:0回答:4
javascript cross-browser svg no-framework
4个回答
8
投票

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

我现在使用以下代码:

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

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

这样我就可以在所有浏览器中一致地通过

getAttribute()
检索属性。


2
投票

你能试试这个吗?

evt.target.getAttributeNode("x").nodeValue
。我在 safari、chrome、Firefox 中尝试过,工作正常。


2
投票

据我所知 Firefox 不支持 SVGElementInstance。

这里有几个来自 w3c SVG 1.1 第二版测试套件的 SVGElementInstance 测试来验证:

您应该做的是,如果 SVGElementInstance 不存在,则提供后备解决方案,这很容易检测到,例如:

if (elm.correspondingUseElement) {
  /* elm is a used instance, not a real element */
} else {
  /* fallback solution */
}

如果元素是 SVGElementInstance,它将具有

correspondingUseElement
属性,否则它将不具有该属性。普通的 svg 元素不会有这个属性,只有使用过的实例才会有它。


0
投票

你尝试过吗

evt.target.getAttributeNS(evt.target.parent.namespaceURI,"x")

© www.soinside.com 2019 - 2024. All rights reserved.