<iframe name="src" width="100%" frameborder=0 scrolling=no src='admin.htm?catId=<c:out value="${model.l}" />'
onload="this.height = document.frames['src'].document.body.scrollHeight" />
例子:
1,創建頁面 test.html 。 頁面中含有一個 iframe,name為 ifrname ,id為 ifrid, src 為 iframe.html頁面。
<iframe src="ifarme.html" name="ifrname" height="" style="" onload="" id="ifrid" scrolling=""> </iframe>
2,創建 iframe.html 頁面,里面含有一些內容。
<p>
這是iframe頁面,通過在父窗口頁面或子頁面添加JS來自動更改寬高,以適應內容的多少。
</p>
要想使iframe自動適應寬和高,可以在 test.html 頁面iframe onload處增加一些JS代碼。如:
<iframe src="ifarme.html" name="ifrname" height="" style="" onload="this.height = document.frames["ifrname"].document.body.scrollHeight" id="ifrid" scrolling=""></iframe>
這樣iframe即可以自動適應高度了。如果不在onload處增加js,那也可以放到頁面上來調用。比如寫個函數。
<script>
function setAutoHeight(iframeElement, iframeWindow) {
iframeElement.style.height = iframeWindow.document.body.scrollHeight;
iframeElement.style.width = iframeWindow.document.body.scrollWidth ;
// 或者
// iframeElement.height = iframeWindow.document.body.offsetHeight ;
// iframeElement.width = iframeWindow.document.body.offsetWidth;
}
//調用函數setAutoHeight();
setAutoHeight( document.getElementById("iframeid"), window.frames[0] );
</script>
這樣也可以達到自適應高寬的目的,在這里要注意的是,iframeElement參數必須是 document.getElementById("iframeid"), iframeWindow參數是 window.frames[0] 或document.frames["ifrname"]。 這是因為通過name得到的對象是窗口(window)對象,非窗口里的iframe對象。同時document.getElementById("iframeid)不能像window對象可以得到window.document。
所以這里最好給iframe分別加上name和id,id用來更改寬高樣式屬性,name用來執行window相關事件如location.href,document.write。bgColor例外,元素對象和窗口對象都可以得到,這是因為他們都有這個屬性。
如果要隱藏iframe滾動條,可以設置iframeWindow.scrolling = "no";但這不能兼容多個瀏覽器,用iframeElement.document.body.style.overflow = "hidden";這種或直接在iframe處增加scrolling="no" html代碼就可以很好地兼容了。
3,如果不能修改父頁面,而只能把代碼增加在iframe頁面里呢?
可以寫個類似函數,放在iframe頁面里:
<script>
function setAutoHeight( parentIframeElement, slefDocument ){
slefDocument.style.overflow = "hidden"; // 隱藏全部滾動條
// document.body.style.overflowY = "hidden"; // 沒有豎滾動條
parentIframeElement.style.height = slefDocument.scrollHeight;
parentIframeElement.style.width = slefDocument.scrollWidth;
}
// 在頁面最后執行
setAutoHeight(parent.document.getElementById("ifrid"), document.body);
// 或onload時執行
//window.onload = function() {
// setAutoHeight(parent.document.getElementById("ifrid"), document.body);
//}
// 或者超時執行
// setTimeout(
// function() {
// setAutoHeight(parent.document.getElementById("ifrid"), document.body);
// },
// 200 );
</script>
4,在線通過iframe更改父窗口里iframe的寬高,因為安全原因會有跨域的問題,若是不在同一域名,那是被禁止的。如果同在一個域名下,但2級域名不同,比如a.yourcompany.com 和b.yourcompany.com。
這時可以通過重新設置document.domain 來跨越2級域名。
var domain = "yourcompany.com";
try {
if( document.domain.indexOf(domain) != -1 ) {
document.domain = domain; // set new document.domain;
}
} catch (ex) {
alert("error: " + ex.toString() );
}
如果域名含有yourcompany.com,則改將document.domain改為yourcompany.com