由於項目中引入了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>