HTML代碼:
| 代碼如下 |
複製代碼 |
|
<iframe src="http://www.fufuok.com/" id="iframepage" name="iframepage" frameBorder=0 scrolling=no width="100%" onLoad="iFrameHeight()" ></iframe> |
Javascript代碼:
| 代碼如下 |
複製代碼 |
|
<script type="text/javascript" language="javascript">
function iFrameHeight() {
var ifm= document.getElementById("iframepage");
var subWeb = document.frames ? document.frames["iframepage"].document : ifm.contentDocument;
if(ifm != null && subWeb != null) {
ifm.height = subWeb.body.scrollHeight;
}
}
</script>
|
代碼二
在包含Iframe的頁面:
| 代碼如下 |
複製代碼 |
|
<iframe src="main.asp" width="557px" height="100%" name="Mainv" id="Mainv" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" style="border:#FFFFFF"></iframe> |
然後在每個要在Iframe中顯示的頁面上,
| 代碼如下 |
複製代碼 |
|
<body onload="parent.document.all.Mainv.height=getTotalHeight();"> |
然後在頁面底部加入
| 代碼如下 |
複製代碼 |
|
<div id="theEnd" style="position:relative"></div>
<script language="JavaScript">
function getTotalHeight(){
return document.getElementById("theEnd").offsetTop+10;
}
</script> |
同域下的iframe自適應高度
同域下父頁面內的js能擷取到iframe頁面的高度,所以在iframe載入完後擷取下高度就行了
| 代碼如下 |
複製代碼 |
<iframe src="./ue.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;width:1000px;" onload="autoHeight();"></iframe>
<script type="text/javascript">
function autoHeight(){
var iframe = document.getElementById("Iframe");
if(iframe.Document){//ie自有屬性
iframe.style.height = iframe.Document.documentElement.scrollHeight;
}else if(iframe.contentDocument){//ie,firefox,chrome,opera,safari
iframe.height = iframe.contentDocument.body.offsetHeight ;
}
}
</script> |
如果是同一個網域名稱下的不同子域,設定下document.domain就行了
IE6和IE7中的iframe沒有contentDocument屬性,而且如果iframe裡的頁面在同域下的不同子域,通過iframe.Document.documentElement.scrollHeight擷取到的高度是錯誤的,所以還是建議用 iframe.contentwindow.document來擷取高度(added at 2010-03-22)
2.跨域下的iframe自適應高度
跨域的時候,由於js的同源策略,父頁面內的js不能擷取到iframe頁面的高度。需要一個頁面來做代理。
方法如下:假設www.a.com下的一個頁面a.html要包含www.b.com下的一個頁面c.html。
我們使用www.a.com下的另一個頁面agent.html來做代理,通過它擷取iframe頁面的高度,並設定iframe元素的高度。
a.html中包含iframe:
| 代碼如下 |
複製代碼 |
|
<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;"></iframe> |
在c.html中加入如下代碼:
| 代碼如下 |
複製代碼 |
|
<iframe id="c_iframe" height="0" width="0" src="http://www.a.com/agent.html" style="display:none" ></iframe>
<script type="text/javascript">
(function autoHeight(){
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var c_iframe = document.getElementById("c_iframe");
c_iframe.src='#'"
})();
</script> |