转载:iframe全跨域高度自适应解决方案

看到这个需求的时候就在暗爽,又可以搞定一个知识点了。哈哈,一天的奋斗之后,果然有所收获,而且经过怿飞的指点,在跨域问题解决上还有所突破(不通过hash)。

Demo,兼容IE,FF,Safari。

方案说明:

需求是:A页面(taobao.com)要嵌入B页面(alibaba.com),因为不能确定B页面的高度,所以要求高度自适应。

解决方法:简单来说就是在B页面里创建一个和A同域的iframe C,让C和A之间可以通讯,以把B的高度传过去。

那么怎么传过去呢?以前的方法是在C里改变parent.parent(即A)的location.hash,但是改hash会生成浏览器历史记录,点后退前进按钮用户体验不佳。我们试了下在A页面直接取frames[b].frames[c].location.hash,居然可以取到。

剩下的就简单了,在A里指定iframe B装载完成后获取C的hash,然后通过hash设置iframe B的高度。

具体代码:

A页面:(基于YUI)

/**
* 待iframe载入后执行函数
*
* @param {Element} el
* @param {Function} func
*/
var onIframeLoad = function(el, func) {
var cb = function() {
try {
func.call(this);
} catch (e) {}
}
if (TB.bom.isIE) {
el.onreadystatechange = function(){
if (el.readyState == 'complete') {
setTimeout(cb, 0);
el.onreadystatechange = null;
}
}
} else {
el.onload = function() {
setTimeout(cb, 0);
el.onload = null;
}
}
};
/**
* 跨域iframe高度自适应封装
*
* @param {String} name
*/
var crossDomainIframe = function(name) {
var iframe = YAHOO.util.Dom.get(name);
var xclient = 'xclient';
onIframeLoad(iframe, function(){
try {
var h = frames[name].frames[xclient].location.hash.substring(1);
if (h == '') {
var func = arguments.callee;
setTimeout(function(){ func(); }, 20);
return;
}
iframe.style.height = h+'px';
} catch (e) {}
});
};
// 执行
crossDomainIframe('frame_content');

B页面:

(function(){
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function adjust() {
var h = document.documentElement.scrollHeight || document.body.scrollHeight;
try {
if (document.getElementById('xclient')) {
var divEl = document.getElementById('xclient').parentNode;
console.log(document.getElementById('xclient').parentNode);
divEl.parentNode.removeChild(divEl);
}
var el = document.createElement('div');
el.innerHTML = '';
document.body.appendChild(el);
} catch(e) {}
}
addLoadEvent(adjust);
})();

C页面:空页面,有个文件避免404发生即可

原文地址:https://www.cnblogs.com/yuzhongwusan/p/1371063.html