---
title: "Iframe自适应高度的js代码"
author: "kunbei"
date: "2011-03-30T09:05:35Z"
tags: []
categories: ["Web前端"]
slug: "iframe-js"
draft: false
lastmod: "2011-03-30T09:05:35Z"
id: 979776
url: "https://kunbei.iteye.com/blog/979776"
---

有不少wBox的用户反映iframe时候不可以自动撑开高度，今天在无意中看到了司徒正美的一片关于iframe自适用高度的js代码，感觉不错，转载来了。


```java
var adjustIframe = function (id) {
    var iframe = document.getElementById(id)
    var idoc = iframe.contentWindow && iframe.contentWindow.document || iframe.contentDocument;
    var callback = function () {
        var iheight = Math.max(idoc.body.scrollHeight, idoc.documentElement.scrollHeight); //取得其高
        iframe.style.height = iheight + "px";
    }
    if (iframe.attachEvent) {
        iframe.attachEvent("onload", callback);
    } else {
        iframe.onload = callback
    }
}

```


HTML代码如下所示：


```java
<iframe id="js_sub_web" width="80%" frameborder="0" scrolling="no" allowTransparency="true" src="http://www.cnblogs.com/rubylouvre/archive/2009/09/15/1566722.html">
</iframe>
```


使用代码：


```java
window.onload = function(){
     adjustIframe("js_sub_web");
}
```