iframe 的跨框架操作一直是個容易踩雷的區域,這裡把 contents() 的用法、父子視窗互操作,以及高度自適應等常見需求整理成一份筆記。
官方說明:搜尋符合元素的所有子節點(包含文字節點)。如果該元素是 iframe,則會搜尋其文件內容。
例如往一個空白框架裡塞內容:
$("iframe").contents().find("body").append("I'm in an iframe!");
$("#mainiframe").contents().find("#someID").html(); // 取得 HTML
$("#mainiframe").contents().find("#someID").text(); // 取得文字
同一頁有兩個 iframe 時,leftiframe 想改 mainiframe 的 src 可以這樣寫:
$("#mainframe", parent.document.body).attr("src", "https://www.baidu.com");
取得父視窗裡某個元素的內容:
$(window.parent.document).find("#xuan").html(x);
若在 iframe 中要直接呼叫父視窗的方法(假設父視窗有個 add 函式):
self.parent.add();
在 IE6、IE7 中可以用 document.frames[ID].document 取得子視窗的 document,但這是非標準寫法,Firefox 不支援。Firefox 走的是 W3C 標準的 document.getElementById(ID).contentDocument;IE8 之後也改用標準寫法了。因此實務上常包成一個相容函式:
function getIFrameDOM(id){
return document.getElementById(id).contentDocument || document.frames[id].document;
}
如果要的是 window 物件而非 document,則改用 document.getElementById(ID).contentWindow,這樣就能呼叫子視窗裡的函式。
父視窗放兩個子框架 wIframeA(a.html)與 wIframeB(b.html):
<div id="pHello">此處可透過 iframeB 的 JavaScript 函式來替換</div> <iframe id="wIframeA" name="myiframeA" src="a.html" scrolling="no" frameborder="0"></iframe> <iframe id="wIframeB" name="myiframeB" src="b.html" scrolling="no" frameborder="0"></iframe>
兩個子視窗都放一個 id 為 hello 的段落方便示範:
<p id="hello">Hello World!</p>
父視窗改子視窗 A 的樣式:
function iframeA(){ // 改變子視窗 A 中 #hello 的背景色
var a = getIFrameDOM("wIframeA");
a.getElementById('hello').style.background = "red";
}
function getIFrameDOM(id){ // 相容 IE、Firefox 的 iframe DOM 取得函式
return document.getElementById(id).contentDocument || document.frames[id].document;
}
子視窗改父視窗的內容,只要在操作前加上 parent 即可;子視窗 B 也可以透過 parent.getIFrameDOM("wIframeA") 拿到 A 的 document,進而改 A 的內容——這正是同源 iframe 之間互相操作的典型套路。
這題困擾過我一段時間,網上的解法品質參差。搭配 jQuery 1.3.2,四行程式碼就能搞定,IE、Firefox、Opera、Safari、Chrome 都通:
function heightSet(thisFrame){
if($.browser.mozilla || $.browser.msie){
bodyHeight = window.frames["thisFrameName"].document.body.scrollHeight;
}else{
bodyHeight = thisFrame.contentWindow.document.documentElement.scrollHeight;
// 也可寫成 document.getElementById("thisFrameId").contentWindow.document.documentElement.scrollHeight
}
document.getElementById("thisFrameId").height = bodyHeight;
}
<iframe id="mainFrame" name="mainFrame" frameborder="0" scrolling="no" src="" onload="heightSet(this)"></iframe>
要留意的是 this 在各瀏覽器的行為不太一致:Firefox 與 IE 必須靠 iframe 的 name 才能取到內部頁面高度,其他瀏覽器則可以直接用 this 或 id。
另外常見的雷是異步時序——如果頁面大量使用 Ajax,動態改變 iframe 高度往往抓不到正確值。一般處理方式是在異步請求的 callback 後面補一行 parent.window.heightSet();,讓父視窗重新計算一次。若對程式碼整潔度要求高,那大概只能考慮脫離 iframe 了。