在网上找了2种方法,经测试都有效,最重要的是要发布后才能看到效果,代码如下:
<div id ="div1">
<iframe src="zencoding test.html" frameborder="0" scrolling="no" width='100%' id="content_iframe" ></iframe>
</div>
<script>
//自适应 iframe 内容高度
function reinitIframe() {
var iframe = document.getElementById("content_iframe");
try {
var userAgent = window.navigator.userAgent; //取得浏览器的userAgent字符串
if (userAgent.indexOf("Chrome") > -1) {
var bHeight = iframe.contentWindow.document.documentElement.scrollHeight;//documentElement 不能替换成body 否则 google浏览器不兼容
} else {
var bHeight = iframe.contentWindow.document.body.scrollHeight;//documentElement 不能替换成body 否则 google浏览器不兼容
}
iframe.height = bHeight;
} catch (ex) {
}
}
window.setInterval("reinitIframe()", 200);
</script>
下面的是点击加载不同的内容,并iframe自适应内容的高度
<div class="demo">
<div class="opt_btn">
<button onclick="getData('iframeH');">加载内容1</button>
<button onclick="getData('iframeH2');">加载内容2</button>
</div>
<iframe src="iframeH.html" id="ifrm" frameborder="0" width="100%" scrolling="no" marginheight="0" marginwidth="0" onLoad="setIframeHeight(this.id)"></iframe>
</div>
对应的js
<script type="text/javascript">
function getData(ifm){
document.getElementById("ifrm").src = ifm+'.html';
}
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
function setIframeHeight(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument? ifrm.contentDocument:
ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px"; // reset to minimal height ...
ifrm.style.height = getDocHeight( doc ) + 4 + "px";
ifrm.style.visibility = 'visible';
}
</script>
同时总结下经常用的高度 contentWindow 兼容各个浏览器,可取得子窗口的 window 对象。 contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 对象。 document.body.clientWidth 可见区域内容的宽度(不包含边框,如果水平有滚动条,不显示全部内容的宽度) document.body.clientHeight 全部内容的高度(如果垂直有滚动条,也显示全部内容的高度) document.body.offsetWidth 可见区域内容的宽度(含边框,如果水平有滚动条,不显示全部内容的宽度) document.body.offsetHeight 全部内容的高度(如果垂直有滚动条,也显示全部内容的高度) document.body.scrollWidth 内容的宽度(含边框,如果有滚动则是包含整个页面的内容的宽度,即拖动滚动条后看到的所有内容) document.body.scrollHeight 全部内容的高度
(adsbygoogle = window.adsbygoogle || []).push({});