现在的位置: 首页 > 综合 > 正文

跨域IFrame自动高度方案(JQuery版)2010年7月修正版

2012年12月17日 ⁄ 综合 ⁄ 共 1391字 ⁄ 字号 评论关闭

    由于项目中引入了JQuery,不方便再引用YUI。所以依照 Session variables without cookies 原理,直接用JQuery实现如下:

    场景:主页面 (emo_windowname.html)一个IFrame(framePreview),在页面加载或者单击按钮时,让IFrame加载一个页面(http://...../正文.html).

    条件:正文.html 预告加入脚本,或者使用HttpModule加入脚本:

Code

    这样,在主页面中,就可以通过window.name把高度取过来,然后设置一下 framePreview的高度。

代码如下:

 

autoHeightIFrameNavigate

/*
* 跨域自动设置IFrame高度 牛昆亮 二○一○年七月十六日
* 需要引用 JQuery
*/
function autoHeightIFrameNavigate(iframeId,url, fnSuccess)
{
var step = 0;
function onload()
{
if(step == 0)
{
var cw = this.contentWindow;
setTimeout(
function(){
try
{
var height = cw.document.body.scrollHeight;
if(height == 0)
{
setTimeout(arguments.callee,
20);
return false;
}

cw.name
= $(this).attr('_name_'); //恢复原来的 Name
iframe.css('height', height + 'px');
step
= 2;
fnSuccess();
}
catch(e)
{
step
= 1;
cw.location
= "about:blank"; //导向代理页面,我直接使用了这个
}

},
0);
}
else if(step == 1)
{
step
= 2;
var cw = this.contentWindow;

var msg = cw.name; //得到值 这个值就是高度了
cw.name = $(this).attr('_name_'); //恢复原来的 Name
cw.location = url; //再次导向目标页面

try
{
var height = eval(msg); //得到并设置高度
//alert(height);
iframe.css('height', height + 'px');

}
catch(e)
{
iframe.css(
'height', '800px');
//alert('目标页面没有设置高度到 window.name')
}
}
else
{
fnSuccess();
}
}

url
= url + (url.indexOf('?') == -1 ? '?':'&') + new Date().valueOf();
step
= 0;
var iframe = $('#' + iframeId);
iframe.attr(
'_name_',iframe.attr('name')) //备份原来的 name
.attr('src',url) //设置URL
.bind('load',onload)
}

 

代码下载:http://files.cnblogs.com/evlon/autoiframeheight.7z

抱歉!评论已关闭.