也谈iframe高度自适应
先描述下我在最近项目中遇到这个问题的场景。
我们的项目是对某款产品的评测,网页下半部分是用户关于这个产品的微博讨论,评论等等,后台开发同事决定将这部分内容全部放在一个iframe里,通过传入不同的产品ID参数就可以在整个项目中共用这部分代码,但这个内嵌框架里的内容全部是动态加载,并且高度不能确定,这就引出了下边要说的iframe高度自适应问题。
主页面iframe代码:
<iframe width="100%" scrolling="no" frameborder="0" src="http://www.abc.com/content.htm" id="ifr_cmnt"></iframe>
iframe内部代码:
<body>
<div id="wrap">
<!--页面其它内容-->
</div>
</body>
JS控制iframe高度自适应方法:
方法一:JQuery选择器。仅在主页面中使用下列代码,这也是代码量最小的一种方法。
document.domain="sina.com.cn";
jQuery("#ifr_cmnt").load(function(){
var set_height = jQuery(this).contents().find("#wrap").height();
jQuery(this).height(set_height);
});
方法二:hash传值。
主页面代码:
document.domain="sina.com.cn";
jQuery("#ifr_cmnt").load(function(){
var temp_height = window.frames['ifr_cmnt'].location.hash;
var set_height = parseInt(temp_height.slice(temp_height.lastIndexOf("#")+1));
jQuery(this).height(set_height);
});
内嵌页面代码:
var ifr_height = jQuery("#wrap").height();
document.location.href+=("#"+ifr_height);
方法三:传统JavaScript。
主页面代码:
document.domain = "sina.com.cn";
jQuery("#ifr_cmnt").load(function(){
var set_height = document.getElementById("ifr_cmnt").contentWindow.document.body.scrollHeight;
document.getElementById("ifr_cmnt").height = set_height;
});
内嵌页面代码:
var ifr_height = jQuery("#wrap").height();
parent.document.getElementById("ifr_cmnt").height = ifr_height;
整个过程需要注意几个细节:
a、当页面中包含来自其他子域的框架或内嵌框架时,通过设置document.domain来实现页面间的JavaScript通信。
b、因为浏览器在渲染页面时存在一些差异,比如内嵌页面中有异步加载的数据块,在IE中,首次渲染不会考虑异步加载内容是否成功,导致数据加载完成后iframe区域由于内容高度增加出现滚动条,在Firefox和Chrome等现代浏览器中不会出现这个问题。



