iframe自适应高度

收获了一段很有用的iframe自适应高度代码。众所周知,iframe的高度显示一直是个难题,默认高度属性只接受简单粗暴的固定值,易用性差。这段代码将可以帮助iframe的父页面自动适应子页面的高度。

将下列代码插入iframe父页面的标签中。

<script type="text/javascript">   
function reinitIframe(){   
var iframe = document.getElementById("frame_content");   
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标签内插入iframe。

<iframe id="frame_content" src="iframe_b.html" scrolling="no" frameborder="0" onload="this.height=100"></iframe>

或者

<iframe id="frame_content" src="iframe_b.html" scrolling="no" frameborder="0" onload="this.height=this.contentWindow.document.documentElement.scrollHeight"></iframe>

该代码分别对IE,Firefox, Opera and Safari进行了测试,效果都很理想。只有Opera有所谓3px的误差。唯一的不足就是不支持跨域,而且在Html Dom的操作上也出现一些问题。所以,如果不进行跨域和Dom操作,这是一个非常理想的对iframe自适应高度的解决方法。

作者:“大米”

发表评论

Clicky