iframe有一個煩人的問題,就是在沒有設定高度的情況下,被嵌套區會顯示一大片空白,有時候設定了高度也不行,後來用JavaScript輕鬆解決了iframe自適應高度的問題,下面把經驗和具體方法分享出來。
為了示範方便,這裡需要2個頁面,一個是被iframe的頁,一個是母頁面,先來看母頁面,也就是有iframe代碼的頁面:
| 代碼如下 |
複製代碼 |
|
<html>
<head>
<title>iframe自適應載入的網頁高度</title>
</head>
<body>
<iframe src="iframe.htm"></iframe>
</body>
</html> |
被iframe的頁面:假設檔案名稱是:iframe.htm,這個檔案裡的代碼為:
| 代碼如下 |
複製代碼 |
|
<html>
<head>
<title>iframe自適應網頁高度</title>
<script type="text/javascript">
function iframeAutoFit()
{
var ex;
try
{
if(window!=parent)
{
var a = parent.document.getElementsByTagName("IFRAME");
for(var i=0; i<a.length; i++) //author:meizz
{
if(a[i].contentWindow==window)
{
var h1=0, h2=0;
if(document.documentElement&&document.documentElement.scrollHeight)
{
h1=document.documentElement.scrollHeight;
}
if(document.body) h2=document.body.scrollHeight;
var h=Math.max(h1, h2);
if(document.all) {h += 4;}
if(window.opera) {h += 1;}
a[i].style.height = h +"px";
}
}
}
}
catch (ex){}
}
if(document.attachEvent)
{
window.attachEvent("onload", iframeAutoFit);
window.attachEvent("onresize", iframeAutoFit);
}
else
{
window.addEventListener('load', iframeAutoFit, false);
window.addEventListener('resize', iframeAutoFit, false);
}
</script>
</head>
<body>
<table border="1" width="200" style="height: 400px; background-color: yellow">
<tr>
<td>iframe自適應載入網頁的高度(多瀏覽器安全色,支援XHTML)</td>
</tr>
</table>
</body>
</html> |
最後補充一個:iframe的高度/寬度,自適應內容。
| 代碼如下 |
複製代碼 |
|
<mce:script language= "Javascript "><!--
window.onload=function()
{
parent.document.all("iframe1").style.height = document.body.scrollHeight;
parent.document.all("iframe1").style.width = document.body.scrollWidth;
}
// --></mce:script> |
注意在iframe.htm頁面中,要使用JS做些設定,這是比較關鍵的,若看不懂不要緊,你可直接把代碼複製到你被iframe的頁面中即可。