js如何獲取iframe頁面內的對象


簡單介紹iframe標簽,所有的瀏覽器都支持<iframe>標簽,iframe 元素會創建包含另外一個文檔的內聯框架(即行內框架)。通常我們常用的iframe標簽的屬性有:width(iframe 的寬度)、height(iframe 的高度)、frameborder(顯示框架周圍的邊框)、src(iframe 中顯示的文檔的 URL)。

那么如何使用js來獲取iframe頁面內的對象呢,以及反過來說內嵌的iframe頁面又該如何得到父級頁面的對象?


注意地方:

  1. 需要在服務器下運行
  2. 父級頁面須保證頁面內容加載完畢,即js獲取iframe頁面內容需要在window.onload中寫

相關方法:

1.父級頁面獲取iframe頁面中的元素對象(關鍵contentWindow):

document.getElementById(iframe的id).contentWindow.document.getElementById(iframe頁面元素id)

2.iframe頁面獲取父級頁面的元素對象(關鍵window.parent):

window.parent.document.getElementById(父級頁面的元素id)

代碼示例:

說明:父級頁面test.html,iframe子級頁面:iframe.html

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1 id="parent">父級頁面</h1>
    <iframe id="myIframe" src="iframe.html"></iframe>
</body>
<script type="text/javascript">
    // document.onclick = function(){
    window.onload = function(){
        var myIframe = document.getElementById("myIframe").contentWindow
                               .document.getElementById("son").innerText;
        console.log(myIframe)   
    }
</script>
</html>

iframe.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1 id="son">子級頁面</h1>
</body>
<script type="text/javascript">
    window.onload = function(){
        var sonText = window.parent.document.getElementById("parent").innerText;
        console.log(sonText);
    }
</script>
</html>

在服務器下打開test.html文件,chrome瀏覽器測試結果:

iframe.html先獲取到它的父級頁面test.html的h1元素的內容“父級頁面”,並輸出在控制台;

然后到text.html頁面獲取iframe.html中的h1元素的內容“子級頁面”,並輸出在控制台。

圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM