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

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

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


注意地方:

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

相關方法:

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

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

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

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瀏覽器測試結果:spa

iframe.html先獲取到它的父級頁面test.html的h1元素的內容「父級頁面」,並輸出在控制檯;code

而後到text.html頁面獲取iframe.html中的h1元素的內容「子級頁面」,並輸出在控制檯。

圖片描述

相關文章
相關標籤/搜索