JS 获取iframe高度的静动态方法
<!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>
效果图:
