관리 메뉴

심재운 블로그

Iframe 높이 resize, 자동 높이 설정 방법 본문

프로그래밍/jQuery

Iframe 높이 resize, 자동 높이 설정 방법

재우니 2014. 4. 3. 19:10

 

아래 블로그 사이트 가면, iframe 사이즈를 자동 조절하는 부분을 알려줍니다.

보통 iframe 에 write 함수를 통해 값을 할당하는 방법이 사용되곤 합니다. 보통 src 경로가 아닌 값을 그냥 던지는 거죠. 그 부분은 이상하게 오픈 소스를 적용해도 높이 값을 제대로 가져오지 못하더군요. 하지만 아래 블로그 내용 대로 , f.contentWindow.document.body.scrollHeight 를 통해 높이 값을 가져올 수 있습니다.

<script type="text/javascript">
// Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
function resizeFrame() {
var f = document.getElementById('childframe');
f.style.height =
f.contentWindow.document.body.scrollHeight + "px";
}
< /script>

 

 

 

Suppose you want to include a child iframe on your page. You'd like to resize the height of the child iframe so that it doesn't show a scrollbar. That is, you want something that looks like this:


Here's one way you can do it. First, make the iframe that you want to include. I made a file "child-frame.html" that looks like this:

<html>
< head> <title>Child frame</title> </head>
< body bgcolor="#000000″>

<font color="#ffffff">
< p>Child frame.</p>
< p>Child frame.</p>
< p>Child frame.</p>
< p>Child frame.</p>
< p>Child frame.</p>
< p>Child frame.</p>
< p>Child frame.</p>
< p>Child frame.</p>
< /font>

</body>
< /html>

Now in the parent frame, you can make code like this:

<html>
< head> <title>Parent frame</title> </head>

<body onload="resizeFrame(document.getElementById('childframe'))" bgcolor="#cccccc">

<script type="text/javascript">
// Firefox worked fine. Internet Explorer shows scrollbar because of frameborder
function resizeFrame(f) {
f.style.height = f.contentWindow.document.body.scrollHeight + "px";
}
< /script>

<p>Parent frame.</p>
< p>Parent frame.</p>
< p>Parent frame.</p>
< p>Parent frame.</p>

<p>
<iframe frameborder=0 border=0 src="./child-frame.html" name="childframe" id="childframe">
</iframe>
< /p>

</body>
< /html>

You can also see a live example of resizing an iframe height dynamically.

What does this code do? When the body of the parent frame loads, it looks up the document element "childframe" which corresponds to the iframe. Then the page calls a function resizeFrame(). The function sets the height of the frame to be the scrollHeight, which effectively removes the scrollbar.

The only tricky bit is the "frameborder=0 border=0″ attributes on the frame. If you leave off the frameborder attribute, Internet Explorer will assume that the frame should have a nonzero border, but it won't include the frame border in the value it returns for scrollHeight. The net effect is that IE will show a scrollbar unless you add "frameborder=0″.

It always annoys me to dive into cross-browser development when it feels like things should be standardized. Looks like it annoys other people too.

Anyway, feel free to rip on my code in the comments, but I was looking for a simple, working example of setting an iframe's height so that the iframe wouldn't have a scrollbar.

 

1 Comments
댓글쓰기 폼