---
title: "JS 获取iframe高度的静动态方法"
author: "onestopweb"
date: "2018-03-30T21:50:28Z"
tags: []
categories: ["Web前端"]
slug: "js-iframe"
draft: false
lastmod: "2018-03-30T21:50:28Z"
id: 2415052
url: "https://onestopweb.iteye.com/blog/2415052"
---

```
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JS 获取iframe高度的静动态方法</title>
<link rel="stylesheet" href="base.css" />
</head>
<body>
<h3>iframe 演示</h3>
<!--默认的-->
<iframe src="demo.html"></iframe>

<!-- 静态获取高度 -->
<iframe src="demo.html" scrolling="no" frameborder="0" id="iframeHei" width="100%"></iframe>
<script type="text/javascript">
function iframeAutoFit(iframeObj){ 
    setTimeout(function(){if(!iframeObj) return;iframeObj.height=(iframeObj.Document?iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200) 
}
window.onload = function () {
    iframeAutoFit(document.getElementById('iframeHei'));
};
</script>

<!-- 动态获取高度，每200毫秒获取一次 -->
<iframe src="demo.html" frameborder="0" scrolling="no" id="iframeHei2"  width="100%" onload="this.height=100"></iframe>
<script type="text/javascript">  
function reinitIframe(){  
	var iframe = document.getElementById("iframeHei2");  
	try{  
		var bHeight = iframe.contentWindow.document.body.scrollHeight;  
		var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;  
		var height = Math.max(bHeight, dHeight);  
		iframe.height =  height;  
	}catch (ex){}  
}  
window.setInterval("reinitIframe()", 200);  
</script>
</body>
</html>
```

 

效果图：

![](http://dl2.iteye.com/upload/attachment/0129/3551/b8d3ddac-3cf3-339f-b845-686990f214b0.jpg)