DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
iframe 用法與注意事項完整整理
編輯:CSS詳解     

iframe 的功能是在一份文件裡內嵌另一份文件,建立一個浮動的框架。很多人對它的控制方式其實只有模糊的概念,這裡一口氣說清楚。

取得 iframe 的兩種方法

假設有一個 id 與 name 都叫 ifr 的 iframe,取得它有兩種寫法:

document.getElementById("ifr");
window.frames["ifr"];

差別在於取到的東西不同。第一種只取回一個 OBJECT;第二種取回的是完整的 DOM 模型。這個區別決定了你能做什麼:

  • 只想改 iframe 的 src、border、scrolling 這類 attribute(注意:attribute 不等於 property,像 scrollHeight、innerHTML 這種 property 是寫不進標籤裡的),用第一種方法。
  • 想操作 iframe 裡的函數或變數,必須用第二種方法,因為它取到的是完整的 DOM 模型。
  • 想取得 iframe 內部頁面(而不是 iframe 本身),例如讀 document.body 的內容,也只能用第二種方法。

還有一點很重要:如果 iframe 的頁面還沒完全載入就存取它的 DOM 模型,會發生相當嚴重的錯誤。所以務必準備容錯機制,例如先確認 readyState 為 complete 再動作。

父頁面範例(aa.htm)

<iframe id="ifr" name="ifr" width="100%" height="500" src="bb.htm"></iframe>

<script type="text/javascript">
var aa_value = "I'm a variant in Top window!";
var ifr_id = document.getElementById("ifr");
var ifr_window = window.frames["ifr"];

alert("從 id 取 iframe 內的變數會失敗:" + ifr_id.bb_var);
alert("從 id 取 iframe 的 window 也是 undefined:" + ifr_id.window);
alert("從 id 可以取到 src:" + ifr_id.src);
alert("從 window 可以取到內部頁面的 href:" + ifr_window.document.location.href);

// 由於 bb.htm 可能尚未載入完成,以下可能引發錯誤
// 呼叫 iframe 內的函數
// ifr_window.bb();

// 讀取 iframe 內的變數
alert("從 window 取 iframe 內的變數:" + ifr_window.bb_var);
alert("從 window 取 iframe 的 body 內容:" + ifr_window.document.body.innerHTML);

function aa(msg){
  alert("I'm alerting from Top window, and I received a msg:\n" + msg);
}
</script>

子頁面範例(bb.htm)

<script type="text/javascript">
var bb_var = "I'm a variable in ifr";

function bb(){
  alert("Alert from iframe: I'm frame ifr's function");
}

// 取得父頁面的變數
alert("parent.ifr_id : " + parent.ifr_id);
alert("parent.aa_value : " + parent.aa_value);

// 透過父頁面的 ifr_id 改變自己的高度
alert("iframe 的 clientHeight : " + document.body.clientHeight);
parent.ifr_id.height = document.body.clientHeight;
alert("iframe 的 scrollHeight : " + document.body.scrollHeight);

// 呼叫父視窗的函數
parent.aa("I will call a function which is Top window's");

// 改變父視窗的標題
alert("I will change Top window's title");
top.document.title = "The title value changed";

// 透過父視窗的 ifr_id 改自己的 border 與 scrolling
alert("I will change my border and scrolling");
top.ifr_id.border = 0;
top.ifr_id.scrolling = "no";
</script>

這段示範了雙向溝通的所有典型操作:父頁讀子頁的變數與 DOM、子頁讀父頁的變數、子頁呼叫父頁的函數、子頁改父頁的標題,以及子頁透過父頁參照調整自己的屬性。

最後提醒一句:iframe 在現代前端開發中已經很少用於頁面排版,主要還留在第三方內容嵌入(廣告、影片、地圖)與沙箱隔離這類場景。若只是為了排版分區,用 CSS 會乾淨得多。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved