代码描述:js操作iframe子页面元素。js获取操作iframe子页面元素代码下载
本章节介绍一下如何如何在父页面操作子页面的元素,或者在子页面中操作父页面中的元素,既然是操作父页面或者子页面中的元素,那么就首先要获取document对象才可以,下面就分别做一下简单介绍。 一.基本准备: 父页面a.html代码:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> </head> <body> <iframe src="b.html" id="iframe"></iframe> <div id="a">51前端一</div> </body> </html>
子页面b.html代码:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> </head> <body> <div id="b">51前端二</div> </body> </html>
二.父页面中操作子页面中的元素: 操作子页面中的元素,首先要获取子页面的document对象,实现此功能的方式有多重,我们只需要掌握一种就可以了,可能多了会造成一定的混乱,代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <script type="text/javascript"> window.onload=function(){ var iframe=document.getElementById("iframe"); //获取子页面中id属性值为b的元素对象 iframe.contentWindow.document.getElementById("b"); } </script> </head> <body> <iframe src="b.html" id="iframe"></iframe> </body> </html>
以上代码可以获取子页面中id属性值为b的元素对象。 contentWindow属性可以获取iframe的window对象,后面的操作就是普通的DOM操作了。 三.子页面中操作父页面的元素:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <script type="text/javascript"> function getParent() { if(window.self != window.top){ var oDoc=window.self.parent.document; oDoc.getElementById("a").style.color="red"; } } getParent() </script> </head> <body> <div id="b">51前端二</div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能