사이트를 만들다 보면 iframe을 사용하여 다른 문서를 삽입해야 할때가 있습니다.
이때 iframe의 크기를 자동으로 조절해야 할때가 있는데 이럴때 Javascript 의 element객체의 속성인 offsetWidth와 offsetHeight 을 이용하여 iframe의 크기를 자동으로 조절할수 있습니다.
아래의 파일을 다운받으시면 main.html, iframe_src.html 이렇게 2개의 파일이 있는데
핵심은 다음과 같습니다.
main.html
<iframe name="iframe_document" id="iframe_document" src="iframe_src.html" width="500" height="600" frameborder="0"></iframe>
iframe_src.html
<div id="iframe_height"></div>
<script type="text/javascript">
var objHeight = document.getElementById("iframe_height").offsetHeight + 20 ;
parent.document.getElementById("iframe_document").style.height = objHeight + "px";
</script>
잠깐 문서에 대해 이야기를 하자면 offsetHeight는 높이를 구하는 부분으로 넓이를 구하려면 offsetWidth 속성을 사용하면 됩니다. 물론 그에 대응하는 iframe의 넓이를 수정하려면 style.height을 style.width로 바꾸면 됩니다.
한가지 주의 하셔야 할것은 두문서가 같은 도메인상에 있어야 하다는 것입니다.
iframe_auto_1.zip
