在网上找了2种方法,经测试都有效,最重要的是要发布后才能看到效果,代码以下:javascript
<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自适应内容的高度html
<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>
对应的jsjava
<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 所有内容的高度浏览器