【问题标题】:Accessing SVG use element child/linked nodes via javascript通过 javascript 访问 SVG 使用元素子/链接节点
【发布时间】:2017-07-12 12:35:47
【问题描述】:

我想要什么

我需要动态操作使用元素的内容。你知道 - 改变它的子树属性/结构或附加事件处理程序和所有这些东西。访问它的 defs 引用并不相同,因为它只会告诉我有关原型结构的一些信息,而对附加到 shadowRoot 的实际使用内容实例没有任何作用。

问题

不知何故,它无法在现代浏览器中完成(除了 ie),或者我只是错过了一些东西。

我尝试了什么

阅读spec 后,我尝试使用 SVGUseElement.instanceRoot、SVGElementInstance.correspondingUseElement 甚至 shadowRoot,但现代浏览器中的 SVGUseElement 实例(除了 ie11)缺少所有 SVG 规范属性,并且 shadowRoot 始终为空(chrome 检查器显示shadowRoot 树正确)。

示例

这是在 ie 中正确运行的示例代码,在其他浏览器旧版本中似乎是 workinghttps://codepen.io/anon/pen/weREWJ

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">
    <defs>
        <circle id="c1" cx="50" cy="50" r="30" fill="green"/>
    </defs>
    <use id="uc1" x="0" y="0" xlink:href="#c1"></use>
    <use id="uc2" x="100" y="100" xlink:href="#c1"></use>
</svg>

let useNode = document.getElementById("uc1");
console.log(useNode.instanceRoot); //undefined
console.log(useNode.shadowRoot); //null
console.log(useNode.correspondingUseElement); //undefined

对应的UseElement

【问题讨论】:

    标签: javascript svg


    【解决方案1】:

    我认为您现在无法在大多数浏览器中可靠地做到这一点。

    由于缺乏浏览器支持,这些属性最初将从 SVG 2 中删除。但是,由于决定让&lt;use&gt; 元素像在 HTML 中一样使用 Shadow DOM,因此其中一些至少可能是 making a comeback eventually in SVG 2

    【讨论】:

    • 根据other question,这种操作是可能的,虽然旧浏览器版本中的 instanceRoot 属性(至少对于 ie,opera 和 chrome)。我不相信现在这是不可能的,也没有向后兼容或基于 shadow dom 的一些新的其他方式。
    • Chrome removed this feature in 2014 for security reasons。由于 Opera 现在使用相同的引擎(自 2013 年以来),它也失去了它。据我所知,没有解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2013-02-02
    • 1970-01-01
    相关资源
    最近更新 更多