---
title: "iframe自动适应高度"
author: "paper"
date: "2012-12-03T10:47:40Z"
tags: []
categories: ["Web前端"]
slug: "iframe"
draft: false
lastmod: "2012-12-03T10:47:40Z"
id: 1740001
url: "https://paper.iteye.com/blog/1740001"
---

1、第一个适应高度的方案

&lt;script type="text/javascript" language="javascript"&gt; 

function iFrameHeight() { 

var ifm= document.getElementById("iframepage");

var subWeb = document.frames ? document.frames\["iframepage"].document : ifm.contentDocument; 

if(ifm != null && subWeb != null) { 

ifm.height = subWeb.body.scrollHeight; 

} 

} 

&lt;/script&gt;

&lt;iframe src="/custom/job/question.do" scrolling="no" style="border: medium none;  width: 710px; overflow: hidden;" id="iframepage" name="iframepage" onLoad="iFrameHeight()"&gt; &lt;/iframe&gt;

2、别人自适应的方案

 &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;  
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;  
&lt;head&gt;  
&lt;meta http-equiv="Content-Type" content="textml; charset=utf-8" /&gt;  
&lt;title&gt;无标题文档&lt;/title&gt;  
&lt;/head&gt;  
&lt;body&gt;  
&lt;script language="javascript" type="text/javascript"&gt;   
function dyniframesize(down) {   
var pTar = null;   
if (document.getElementById){   
pTar = document.getElementById(down);   
}   
else{   
eval('pTar = ' + down + ';');   
}   
if (pTar && !window.opera){   
//begin resizing iframe   
pTar.style.display="block"   
if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight){   
//ns6 syntax   
pTar.height = pTar.contentDocument.body.offsetHeight +20;   
pTar.width = pTar.contentDocument.body.scrollWidth+20;   
}   
else if (pTar.Document && pTar.Document.body.scrollHeight){   
//ie5+ syntax   
pTar.height = pTar.Document.body.scrollHeight;   
pTar.width = pTar.Document.body.scrollWidth;   
}   
}   
}   
&lt;/script&gt;   
&lt;iframe src ="b.html" frameborder="0" marginheight="0" marginwidth="0" frameborder="0" scrolling="auto" id="ifm" name="ifm" onload="javascript:dyniframesize('ifm');" width="100%"&gt;   
&lt;/iframe&gt; 

&lt;/body&gt;  
&lt;/html&gt;