構建 B/S 系統時,主頁面 index.html 中常要嵌套其他頁面。雖然不少庫已提供控件(如 jQuery EasyUI),但 iframe 的使用仍不可避免。本文按場景給出幾個比較實用的方案。
為什麼是「三談」?一是這話題確實被說爛了,二是多年前就有前輩寫過《再談 iframe 自適應高度》。之所以再提,是因為項目中確實遇到過方方面面,值得總結。
場景一:同域、子頁面高度不會動態增加
最簡單,直接獲取子頁面實際高度並設置給 iframe。兩點注意:一是若頁面有絕對定位或未清浮動的元素,不同瀏覽器(含 Webkit 內核)處理結果可能不同,需做瀏覽器檢測或用 Math.max 取最大值;二是 iframe 內頁面可能很大、加載慢,最好在 onload 事件中計算高度,且 IE 下必須用 obj.attachEvent 綁定 onload:
(function(){
var frame = document.getElementById("frame_content_parent"),
setIframeHeight = function(){
var frameContent = frame.contentWindow.document,
frameHeight = Math.max(frameContent.body.scrollHeight,frameContent.documentElement.scrollHeight);
frame.height = frameHeight;
};
if(frame.addEventListener){
frame.addEventListener("load",setIframeHeight,false);
}else{
frame.attachEvent("onload",setIframeHeight);
}
})();
場景二:同域、子頁面高度會動態增加
原理相同,多加一個計時器持續檢測,當子頁高度與 iframe 高度不一致時重新設置,並用 try 在 JS 出錯時給一個足夠的兜底高度:
(function(){
var _reSetIframe = function(){
var frame = document.getElementById("frame_content_parent")
try {
var frameContent = frame.contentWindow.document,
bodyHeight = Math.max(frameContent.body.scrollHeight,frameContent.documentElement.scrollHeight);
if (bodyHeight != frame.height){
frame.height = bodyHeight;
}
}
catch(ex) {
frame.height = 1800;
}
}
if(frame.addEventListener){
frame.addEventListener("load",function(){setInterval(_reSetIframe,200);},false);
}else{
frame.attachEvent("onload",function(){setInterval(_reSetIframe,200);});}
})();
場景三:同域、動態增高,且腳本可能完全失效
上面的方案考慮了出錯,但萬一腳本根本不執行呢?為此通常預設一個足夠的高度,寫在 CSS 裡(如 #frame_content_parent{ height:1800px; })更方便維護。注意:樣式表裡的樣式不能直接用 node.style 取,微軟模型要用 node.currentStyle,W3C 模型要用 window.getComputedStyle。此外,當 iframe 高度大於內容時各瀏覽器處理不一:Firefox 下 html 高度等於 iframe 高度,而 IE 下取到的是引用頁面的實際高度。
場景四:跨域
跨域時父子頁無法直接互訪,可用「代理頁」繞道。設主頁 A、子頁 B、代理頁 C,其中 A 與 B 跨域、A 與 C 同域、B 與 C 跨域。思路是讓 B 自己算高度,再想辦法告訴 C,由 C 告訴 A。B 頁腳本生成一個隱藏 iframe,把高度拼到代理頁 C 的地址後(用 # 錨點傳值):
//B 頁面腳本
(function(){
var agent_iframe = document.createElement("iframe"),
b_height = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);
agent_iframe.src = "https://demo.zhouqicf.com/js/2010/iframe_height/agent_iframe_once.html#" + b_height;
document.body.appendChild(agent_iframe);
agent_iframe.style.display = "none";
})();
C 頁腳本從 location.hash 取出高度,賦給 A 頁的 iframe:
window.top.document.getElementById("frame_content_parent").height = parseInt(window.location.hash.substring(1),10);
場景五:跨域、子頁高度動態變化
結合場景二與四:B 頁用計時器不停算高度,一旦變化就改代理 iframe 的 src 錨點,C 頁也用計時器監聽 src 變化來調整 A 的 iframe 高度。注意僅改錨點值頁面不會刷新,這正是 C 頁要加計時器的原因。另一種做法是讓 iframe 每次重新請求(C 頁就不用計時器),但要給 src 加隨機參數,否則兩次高度相同時瀏覽器可能不重新請求,腳本也就不跑了。