【问题标题】:document.getElementById results in null where moving svg into object tagdocument.getElementById 导致 null 将 svg 移动到对象标记中
【发布时间】:2014-06-09 22:04:07
【问题描述】:

我正试图通过将我的 html 文档使用的 SVG 文件移动到一个对象标签中来使我的 html 文档成为一种更愉快的阅读体验。

SVG 的部分目的是让它可点击——这反过来会改变它的颜色。这是通过 JavaScript 完成的。

只要 SVG 在父 html 中,一切就可以正常工作,但只要我尝试使用对象标签 JavaScript getElementById 就会失败(console.log(svg_rectangle) 返回 null)。我假设 DOM 不再知道 SVG 元素一旦移动到 Object 标签中,所以它与范围有关?

在谷歌上搜索这个不太幸运,我不是 DOM 专家,所以也许我没有使用正确的关键字。

我通过 Django 运行它,因此是 {{ STATIC_URL }}。

HTML

<html>
<body>

<object id="svg1" data="{{ STATIC_URL }}svg/test.svg" type="image/svg+xml"></object>

<!--
<svg
id="svg_square"
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 height="256"
 width="256"
 version="1.1"
 xmlns:cc="http://creativecommons.org/ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/">

<g class="region">
    <rect id="rect_front" transform="scale(1,-1)" height="64" width="64" y="-128" x="64" onclick="parent.testFunction(this.id)"/>
</g>
</svg>
-->

<script src="{{ STATIC_URL }}archive_140520/handle_svg.js" type="text/javascript"></script>

</body>
</html>

JavaScript

function testFunction(id){
    console.log(id)
    var svg_rectangle = document.getElementById(id);
    console.log(svg_rectangle)
    svg_rectangle.style.fill="green"
}

SVG (test.svg)

<svg
id="svg_square"
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 height="256"
 width="256"
 version="1.1"
 xmlns:cc="http://creativecommons.org/ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/">

<g class="region">
    <rect id="rect_front" transform="scale(1,-1)" height="64" width="64" y="-128" x="64"        onclick="parent.testFunction(this.id)"/>
</g>
</svg>

【问题讨论】:

    标签: javascript svg getelementbyid object-tag


    【解决方案1】:

    您需要寻址objectcontentDocument 以获取其内部元素,请尝试以下操作:

    var svg_rectangle = document.getElementById("svg1").contentDocument.getElementById("svg_square");

    【讨论】:

    • 啊,谢谢,那行得通。 contentDocument 对我来说是一个新的,但现在这很有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2023-03-05
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多