---
title: "Iframe框架高度自适应的实现"
author: "leyoo"
date: "2010-10-11T10:35:52Z"
tags: []
categories: ["编程语言"]
slug: "iframe"
draft: false
lastmod: "2010-10-27T14:38:49Z"
id: 781114
url: "https://leyoo.iteye.com/blog/781114"
---

Iframe框架高度自适应的实现
  
    Iframe框架高度自适应的实现,一个很牛的团队写的，简单的说就是 在A.html中iframe引用B.htm(高度是不断变化的)并且自适应高度.网上也有很多方法，但是有些不全兼容ie6,ie7,ff,opera,在此贴下兼容ie6,ie7,ff,opera下的高度自适应的代码,并且已经封装好，只需要在被引用的页面加入这段代码<script type=”text/javascript” src=”iframeAutoFit.js” mce_src=”iframeAutoFit.js”></script> 

function iframeAutoFit() 
{ 
try 
{ 
if(window!=parent) 
{ 
var a = parent.document.getElementsByTagName_r("IFRAME"); 
//返回一个有特定标签名称（iframe）的子元素列表，是数组对象。 
for(var i=0; i<a.length; i++) 
{ 
if(a*.contentWindow==window)//contentWindow属性是指指定的frame或者iframe所在的window对象 
{ 
  
var h1=0, h2=0, d=document, dd=d.documentElement; 
a*.parentNode.style.height = a*.offsetHeight +"px"; 
//parentNode 属性:传回目前节点的父节点. 
//offserHeaight 属性:表示课件高度 
a*.style.height = "10px"; 
  
if(dd && dd.scrollHeight) h1=dd.scrollHeight;//scrollHeight属性:网页正文全文高 
if(d.body) h2=d.body.scrollHeight; 
var h=Math.max(h1, h2);//取得最大值 
  
if(document.all){h += 0;} 
if(window.opera){h += 1;}//修正在opera浏览器 
a*.style.height = a*.parentNode.style.height = h +"px"; 
} 
} 
} 
} 
catch (ex){} 
} 
if(window.attachEvent) 
{ 
window.attachEvent("onload", iframeAutoFit); 
//页面加载完后执行LoadImg函数 
} 
else if(window.addEventListener)//兼容ff 
{ 
window.addEventListener('load', iframeAutoFit, false); 
}