4

HTML ドキュメントで使用する SVG ファイルを object タグに移動することで、HTML ドキュメントをより快適に読めるようにしようとしています。

SVG の目的の 1 つは、クリック可能にすることです。これにより、色が変わります。これは JavaScript を介して行われます。

SVG が親 html 内にある限り問題なく動作しますが、オブジェクト タグ JavaScript getElementById を使用しようとするとすぐに失敗します (console.log(svg_rectangle) は null を返します)。オブジェクトタグに移動されたSVG要素をDOMが認識しなくなったと仮定しているので、スコープと関係がありますか?

これをグーグルで検索すると、私は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>
4

1 に答える 1

5

内部要素を取得するには、 contentDocumentofに対処する必要があります。次のようなものを試してください。object

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

于 2014-06-09T23:08:46.030 に答える