1、目的
系統通過一內嵌頁面(iframe)
來展現網頁內容(也包括內嵌頁中再嵌一個網頁),這將會引起如下幾個問題:
a.不同的網頁內容多少不一致,導致iframe的高度無法與實現內容或瀏覽器高度相匹配。
b.窗口縮放時,不能iframe不能進行自動調整。
針對這兩個問題,寫了一些js方法,使iframe自動適應內容或瀏覽器高度。
2、js代碼
在主框回頁面中包括如下js方法:
/**
* 內嵌頁面的高度設置
*/
function handleFrameLoad() {
var hDoc = getBodyHeight(document);
var tblmain = document.getElementById('tblMain');
var mFrame = window.mainFrame;
var hFrameDoc = getFrameHeight(mFrame);
var hTable = hDoc-80; //減去該頁面除iframe外其他控件所占的高度.
if(hFrameDoc > hTable) hTable = hFrameDoc;
tblmain.style.height = hTable;
mFrame.height = hTable;
if(window.mainFrame.moduleRight != null){
//表示該內嵌頁,包含內嵌的頁面,頁iframe的id固定為moduleRight。
initFrameHeight(mFrame,hTable);
}
}
/**
* 獲取當前頁面的高度
*/
function getBodyHeight(doc){
if(doc.all) return doc.body.offsetHeight;
else return doc.body.scrollHeight;
}
/**
* 獲取內嵌頁中的高度.
* 若另含子內嵌(moduleRight)頁時,應考慮該頁面的高度.
*/
function getFrameHeight(mFrame){
var h1 = mFrame.document.body.offsetHeight;
var h2 = mFrame.document.body.scrollHeight;
if(mFrame.moduleRight != null){
var h3 = mFrame.moduleRight.document.body.scrollHeight;
if(h3 > h2) h2 = h3;
}
return h2;
}
/**
* 設置子內嵌頁面的高度.
* 通過設置iframe所在table的高度來調整。
*/
function initFrameHeight(frame,hFrame){
var tbl = frame.document.getElementById('tblMainFrame');
tbl.style.height = hFrame;
}
3、其他設置
主頁面(main.jsp),在加載完畢(onload)、窗口大小調整(onresize),以及iframe的加載完畢時,需調用:handleFrameLoad,代碼如下:
<html>

<body onload="handleFrameLoad();" onResize="handleFrameLoad();">

<iframe src="" id="mainFrame" name="mainFrame" border=0 width=100% height=100% frameborder="0" marginwidth="0" hspace="0" scrolling="no" onload="handleFrameLoad();"/>

</body>
</html
其他內嵌頁如下(注:此處的iframe高度設為100%,其高度由父頁面通過設置table<
tblMainFrame>的高度來進行調整):
<html>

<body class="body" style="overflow:hidden;margin:0px;padding:0px">
<table width="100%" height="100%" id="tblMainFrame" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td id='content' height=100%>
<iframe src="about:blank" width="100%" height="100%" name="moduleRight" id="moduleRight" frameborder="0" hspace="0"/>
</td>
</tr>
</table>
</body>
</html
4、樣例下載:
sample
posted on 2008-01-17 13:56
josson 閱讀(9302)
評論(2) 編輯 收藏 所屬分類:
web開發