您的位置:首页 > 其它

iframe高度自动适应

2011-07-12 13:55 295 查看
最近在用iframe嵌套页面,可是由于页面高度不一样,显示就不美观了!后来同事在网上找了很久,终于找到了解决办法,我在这里记录下,以便日后查看。
1.非跨域实现
有A.html和B.html两个页面,A.html中引入B.html:如:
<iframe widht="100%" frameborder="0" scrolling="no" src="B.html" onload="this.height=Math.max(this.windowContent.document.body.scrollHeight,this.windowContent.document.documentElement.scrollHeight)+10"><iframe>
注:有些浏览器不支持boby,所以就改成documentElement了

2.跨域实现
有A.html 、B.html、 C.html三个页面,A.htm和B.html不同域
如:http://www.baidu.com/A.html
http://www.google.com/B.html
实现A.html 嵌入B.html,在可以操作B.html的情况下,引入一个中介页面C.html
(1)A.html中引入:
<iframe width="0" height="0" frameborder="0" scrolling="no" src=" http://www.google.com/B.html" id="frame_content"></iframe> (2)B.html中引入:
<script type="text/javascript">
if(window.top!=window.self){ //判断当前窗口是不是顶层窗口,换句话说,判断当前窗口有没有被嵌套到其他窗口中,如果没,就是顶层窗口
document.write('<iframe src="" width="0" height="0" frameborder="0" scrolling="no" style="display:none" id="frameC"></iframe>');
window.onload=function(){
var hsahH=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)+10;
var urlC=http://www.baidu.com/C.html;
var url=urlC+"#"+hashH;
document.getElementById("frameC").src=url;
}
}
</script>
(3)C.html引入
<script type="text/javascript">
function fn(){
var iObj=document.getElementById("frame_content");
if(iObj){
var hObj=window.location.hash;
if(iObj && hObj.indexOf("#")!=-1){
var hei=hObj.split("#")[1];
if(hei!=""){
iObj.style.height=hei+"px";
}
}
}
}
fn();
</script>
原理:
A.html与B.html不是同一个域,所以不能获取到B.html的高度
B.html嵌入C.html,把高度传给它;
这样由于C.html与A.html是同域,故A.html就可以获取到B.html的高度了;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: