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元素的内容“子级页面”,并输出在控制台。

图片描述

猜你喜欢

转载自www.cnblogs.com/10manongit/p/12920249.html