首页 / 脚本样式 / jQuery / JQuery实现跨域IFrame自动高度方案
JQuery实现跨域IFrame自动高度方案2011-11-10 博客园 阿牛由于项目中引入了JQuery,不方便再引用YUI。所以依照 Session variables without cookies 原理 ,直接用JQuery实现如下:场景:主页面 (emo_windowname.html)一个IFrame(framePreview), 在页面加载或者单击按钮时,让IFrame加载一个页面(http://...../正文.html).条件:正 文.html 预告加入脚本,或者使用HttpModule加入脚本:$(function(){
window.name = document.body.scrollHeight;
});
这样,在主页面中,就 可以通过window.name把高度取过来,然后设置一下 framePreview的高度。代码如下:主 页面代码<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF- 8">
<title>跨域IFrame自动高度</title>
<script language="javascript" src="../Library/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function autoHeightIFrameNavigate (iframeId,url)
{
var iframe = $("#" + iframeId);
iframe.attr("_name_",iframe.attr("name")) //备份原来的 name
.attr("src",url) //设置URL
.one ("load",function () {
this.contentWindow.location = "about:blank"; //导向代理页面,我直接使用了这个
$(this).one("load",function () {
var msg = this.contentWindow.name; //得到值 这个值就是高度了
this.contentWindow.name = $(this).attr("_name_"); //恢复原来的 Name
this.contentWindow.location = url; //再次导向目标页面
try
{
var height = eval(msg); //得到并设置高度
alert(height);
iframe.css("height", height + "px");
}
catch(e)
{
alert("目标页面没有设置高度到 window.name")
}
})
})
}
$(function () {
$("#btnNavigator").click(function(){
autoHeightIFrameNavigate("iframePreview", $("#tbUrl").val());
});
})
</script>
</head>
<body>
<input type="text" id="tbUrl" style="width:100%" NAME="tbUrl" value="http://10.120.147.47/FileUp/e8aa5d05-c682-4913-8f57- f49d0c6e01b5/html/%e6%ad%a3%e6%96%87.html"/>
<input type="button" id="btnNavigator" id="btnNavigator" value="转到" />
<p>
在ie 7, firfox 3.0.10 测试通过。
</p>
<div>
<iframe id="iframePreview" style="width: 100%;height:800px;" scrolling="no" frameborder="no"></iframe>
</div>
</body>
</html>