简单介绍iframe标签,全部的浏览器都支持<iframe>标签,iframe 元素会建立包含另一个文档的内联框架(即行内框架)。一般咱们经常使用的iframe标签的属性有:width(iframe 的宽度)、height(iframe 的高度)、frameborder(显示框架周围的边框)、src(iframe 中显示的文档的 URL)。
那么如何使用js来获取iframe页面内的对象呢,以及反过来讲内嵌的iframe页面又该如何获得父级页面的对象?javascript
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元素的内容“子级页面”,并输出在控制台。