關於iframe載入完畢的判斷介紹了關於iframe載入完成的判斷方法
iframe中跨域載入頁面,在父級頁面由於跨域的限制是訪問不了載入頁面的window對象,也就調用不了子頁面中聲明的函數。
因此在父級頁面中判斷iframe是否載入完畢最初的方式是使用參照元素載入完成的方式:
| 代碼如下 |
複製代碼 |
var loginiframe = document.createElement("iframe");
loginiframe.src = "http://login.hxsd.com/";
loginiframe.onload = function(){
alert("load");
}
document.body.appendChild(loginiframe);
|
但是上面這種方式在ie瀏覽器下在loginiframe載入完成後卻沒有響應,對ie瀏覽器做了其他的處理:
| 代碼如下 |
複製代碼 |
var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1;
var loginiframe = document.createElement("iframe");
loginiframe.src = "http://login.hxsd.com/";
if (isIE){
loginiframe.onreadystatechange = function(){
if (loginiframe.readyState == "complete"){
alert("load");
}
};
} else {
loginiframe.onload = function(){
alert("load");
};
}
document.body.appendChild(loginiframe);
|
問題解決後,通過閱讀《Iframes, onload, and document.domain》,在IE下對於iframe的onload的支援是隱性的,最終解決方式:
| 代碼如下 |
複製代碼 |
|
var loginiframe = document.createElement("iframe");
loginiframe.src = "http://login.hxsd.com/";
if (loginiframe.attachEvent){
loginiframe.attachEvent("onload", function(){
alert("load");
});
} else {
loginiframe.onload = function(){
alert("load");
};
}
document.body.appendChild(loginiframe); |
下面是介紹載入完成後使iframe高度自適應
具體的實現代碼如下:
| 代碼如下 |
複製代碼 |
|
function loadFrame(oFrame, sFrameSrc) {
oFrame.src = sFrameSrc;
if (oFrame.attachEvent){
oFrame.attachEvent("onload", function(){
autoChangeFrameHeight(oFrame);
});
} else {
oFrame.onload = function(){
autoChangeFrameHeight(this);
};
}
}
function autoChangeFrameHeight(oFrame) {
var nHeight = Math.max(oFrame.contentWindow.document.body.scrollHeight, oFrame.contentWindow.document.documentElement.scrollHeight);
oFrame.height = nHeight;
} |
以上方法只適用於同域的連結,在iframe內的內容載入完成後會擷取iframe內的高度賦值給iframe的高度
對於跨域的情況,由於瀏覽器安全性的設定,不同域的頁面之間是不能通訊的,解決的方法是需要通過在iframe調用的頁面中構建一個與父級頁面同域的頁面,通過url的形式將子頁面的高度傳遞過去,具體代碼如下:
子頁面中:
| 代碼如下 |
複製代碼 |
|
window.onload = function() {
var oFrame = document.createElement("iframe");
var nHeight = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);
document.body.appendChild(oFrame);
oFrame.src = "http://PARENT_DOMAIN/agentFrame.html?height=" + nHeight;
oFrame.style.display = "none";
}
代 |
理頁面中:
| 代碼如下 |
複製代碼 |
var nHeight = location.href.match(/?height=(d+)$/)[1];
window.top.document.getElementById("frame").height = nHeight;
|
其中window.top為調用的最頂層視窗