2009. 5. 25. 11:57

Resizing an iframe according to its contents

This code will only work on Microsoft Internet Explorer 5.5+, Mozilla Firebird, and Netscape 7 (as far as I know).

After we learned how to create an iframe with a height of 100%, I'll show you how to create an iframe that gets its height according to the contents of the page that is in it.
That way if you have a long page inside your iframe then your iframe will be tall enough so that you can scroll the external page without scrolling the iframe itself.
You may find this useful in certain cases but I recommend not using it unless you really need it (since you may miss the entire point of using an iframe in the first place).

The Code

In the head of your document enter the following JavaScript code:
<script language="JavaScript">
<!--
function calcHeight()
{
  //find the height of the internal page
  var the_height=
    document.getElementById('the_iframe').contentWindow.
      document.body.scrollHeight;

  //change the height of the iframe
  document.getElementById('the_iframe').height=
      the_height;
}
//-->
</script>

and in the body create the iframe tag:
<iframe width="700" id="the_iframe" 
	onLoad="calcHeight();" 
	src="testing_page.shtml" 
	scrolling="NO" 
	frameborder="1" 
	height="1">
An iframe capable browser is 
required to view this web site.
</iframe>

If you decide to use this code all I ask is that you let me know. 

Thanks to all the people who sent me their comments on this code and helped me improve it :o)

이 코드 사용시 주의점 : 이 코드를 사용하게 되면 코드를 사용한다고 저자에게 알려주면 좋겠다 함.

출처 : http://guymal.com/mycode/iframe_size/
관련 한글 사이트 : http://www.webmini.net/19888


Update : 2009-06-23

위 코드로 제대로 동작하지 않을때가 있다. iframe src 가 동적으로 변경되는 경우. 이때는 다음과 같이 하여 해결하였다.

<script type="text/javascript" language="javascript" >

<!--

    function autoResize(obj)

    {

        param = "TimeFunc('" + obj.id + "')";

        setTimeout(param, 10);

    }

   

    function TimeFunc(name)

    {

        obj = document.getElementById(name)

        cwindow = (obj).contentWindow;

        if (cwindow != null)

        {

            var iframeHeight=

                    (obj).contentWindow.document.body.scrollHeight;

            (obj).height = iframeHeight;

        }

    }

-->

</script>

 

<iframe id="test" src="" scrolling="auto" onload="javascript:autoResize(this)"  width="100%" frameborder="0" height="0" ></iframe>