2014-06-09 2 views
2

객체 태그로 사용하는 SVG 파일을 옮겨서 HTML 문서를보다 즐겁게 읽으려고합니다.document.getElementById는 null을 반환합니다. svg를 객체 태그로 이동합니다.

SVG의 목적 중 하나는 클릭 할 수있게하는 것입니다. 그러면 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> 

자바 스크립트

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

SVG (test.svg) 당신이 뭔가를 시도, 그 내부 요소를 얻을 수 objectcontentDocument를 해결해야

<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> 

답변

2

:

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

+0

감사합니다. contentDocument는 나를위한 새로운 것이었지만 지금은 이해가됩니다. – jayuu

관련 문제