×

跨域的iframe自适应高度

作者:Terry2012.10.22来源:Web前端之家浏览:19300评论:1
关键词:跨域iframe

个人中心使用iframe嵌入了四种直达区,这些直达区的高度是不同的,需要做到自动延展
个人中心所在域是u.soso.com
直达区所在的域是www.soso.com

如果是同域的两个页面a和b,可以在a中插入如下js代码

var iframe=document.getElementById('xx_iframe');
iframe.onload = iframe.onreadystatechange = function(){
try {
if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
if (iframe) {
iframe.height = iframe.contentWindow.document.documentElement.scrollHeight;
//以下为了浏览器兼容
if (iframe.contentDocument && iframe.contentDocument.body.offsetHeight) {
iframe.height = iframe.contentDocument.body.offsetHeight;
}
else {
if (iframe.document && iframe.document.body.scrollHeight) {
iframe.height = iframe.Document.body.scrollHeight;
}
}
}
}
}
catch (ex) {
}
}

即响应iframe的onreadystatechange和onload事件,从iframe节点的documentElement属性,取得b页面的scrollHeight,然后修改iframe的高度

但这个办法在跨域时是行不通的,因为,浏览器会根据安全原因,禁止使用iframe.contentDocument的属性

在这个问题中,有个简单的方式可以解决,即在a页面和b页面中,均使用

document.domain=”soso.com”;

这样,绝大部分浏览器会认为两个页面是同域的,opera除外

为了兼容opera和真正做到跨域iframe的自适应高度(为将来嵌入qq.com的页面做准备),引入一个放在u.soso.com的页面c。

b中嵌入个iframeC,地址是页面c


window.onload=function(){
if(Browser.opera){
var hashH = document.documentElement.scrollHeight;
var urlC = "http://u.soso.com/icenter/htdocs/proxy.html";
document.getElementById("iframeC").src=urlC+"#"+IFM_ID_IN_A
+"_"+hashH;
}
}

关键在于最后一行,在window.onload时,将自身窗口的高度,设在iframe的src的“#”号之后

页面c中有如下代码:

document.domain = "soso.com";
var hash_url = window.location.hash;
var hash_height = hash_url.split("#")[1] + "px";
var IFRAME_ID_IN_A = hash_url.split("#")[0];
var a_iframe = parent.parent.getElementById(IFRAME_ID_IN_A);
a_iframe.height=hash_height;


由于页面c与页面a同域,所以可以修改页面a中某一个iframe的高度,没有了跨域问题,也解决了opera的兼容问题

这种做法会多发一个到c页面的请求,而目前还没有完全跨域的iframe的情况,所以目前仅在浏览器判断为opera的情况下执行

来源:http://blog.webshuo.com

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/%E8%B7%A8%E5%9F%9F%E7%9A%84iframe%E8%87%AA%E9%80%82%E5%BA%94%E9%AB%98%E5%BA%A6.html

网友评论文明上网理性发言已有1人参与

发表评论:

评论列表