1.同域名下Iframe自适應高度的處理
當然此處我用的是Asp.Net MVC 此處src設定為路由結構
用到的就是iframe嵌套的頁面加載完畢的時候,運用onload事件來擷取嵌套在iframe中網頁的高度,然後指派給Iframe的高度即可。
2.跨域時Iframe高度自适應
在首頁面和被嵌套的iframe為不同域名的時候,就稍微麻煩一些,需要避開JavaScript的跨域限制。
iframe首頁面main.html
<head><title>iframe首頁面</title></head>
<body>
<div style="border:1px solid #ccc;padding:10px;">
<iframe id="frame_content" name="frame_content" src="iframe.html" width="100%" height="0" scrolling="no" frameborder="0"></iframe>
</div>
<br />尾部<br />
</body>
</html>
iframe嵌套頁面iframe.html
<head><title>被iframe嵌套頁面</title></head>
文字<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<iframe id="iframeC" name="iframeC" src="" width="0" height="0" style="display:none;" ></iframe>
<script type="text/javascript">
function sethash(){
hashH = document.documentElement.scrollHeight;
urlC = "agent.html";
document.getElementByIdx("iframeC").src=urlC+"#"+hashH;
}
window.onload=sethash;
</script>
iframe中介頁面agent.html
<head><title>iframe中介頁面</title></head>
<script>
function pseth() {
var iObj = parent.parent.document.getElementByIdx('frame_content');
iObjH = parent.parent.frames["frame_content"].frames["iframeC"].location.hash;
iObj.style.height = iObjH.split("#")[1]+"px";
pseth();
代碼裡,kimi可能路徑表示不全
main.html 與 agent.html 是必須同一個域裡
而iframe.html在另一個域