DIV CSS 佈局教程網

JS 獲取並操作 iframe 中元素的方法
編輯:關於JavaScript     

在使用 iframe 進行頁面布局時,我們經常需要從一個頁面獲取並操作另一個 iframe 內部的元素。由於涉及不同瀏覽器的差異,這裡整理幾種常見的獲取方式,並透過一個實際案例說明如何操作 iframe 中的元素。

獲取/設置 iframe 內物件的幾種方法

1、IE 專用(透過 frames 索引定位):

document.frames[i].document.getElementById('元素的ID');

2、IE 專用(透過 iframe 名稱定位):

document.frames['iframe的name'].document.getElementById('元素的ID');

以上方法不僅對 iframe 適用,對 frameset 裡的 frame 同樣適用。IE 雖然善於自定標準,但也提供了一個簡潔且形象化的寫法。

3、通用方法:

document.getElementById('iframe的ID').contentWindow.document.getElementById('元素的ID')

注意要加上 contentWindow,很多問題都是因為忽略了它而出現——它代表 frame 和 iframe 內部的視窗物件。

獲取 iframe 文檔內容

<script type="text/javascript">
function getIframeContent(){ //獲取 iframe 中文檔內容
    var doc;
    if (document.all){ // IE
        doc = document.frames["MyIFrame"].document;
    }else{ // 標準
        doc = document.getElementById("MyIFrame").contentDocument;
    }
    return doc.body.innerHTML;
}
</script>

注意:上面的 .contentDocument 相當於 .contentWindow.document!

實際案例:跨 iframe 操作元素

需求與問題:在網站後台管理中使用了 iframe 框架布局,包括頂部菜單、左側導航和主頁面。需求是:點擊主頁面的按鈕後,在頂部菜單欄右側顯示「退出」鏈接。問題在於:如何在主頁面(mainPage.htm)中獲取並操作頂部菜單頁(topPage.htm)中的 HTML 元素?

解決思路:Window 物件表示瀏覽器中打開的視窗,如果文檔包含框架,瀏覽器會為每個框架創建額外的 window 物件。透過 JS 操作這些 Window 物件即可實現:

function ShowExit() {
    //獲取 iframe 的 window 物件
    var topWin = window.top.document.getElementById("topNav").contentWindow;
    //透過獲取到的 window 物件操作 HTML 元素,這和普通頁面一樣
    topWin.document.getElementById("exit").style.visibility = "visible";
}

說明:第一步,透過 window.top.document.getElementById("topNav") 獲取頂部菜單頁所在的 iframe 物件;第二步,透過該 iframe 物件的 contentWindow 屬性得到元素所在的 window 物件;第三步,透過這個 window 物件操作 iframe 中的元素,操作方式與普通 HTML 元素完全一致。

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