原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法
原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法
发布时间:2016-12-30 来源:查字典编辑
摘要:用原生js在父页面获取iframe子页面的元素,以及在子页面获取父页面元素,这是平时经常会用到的方法,这里写一个例子来总结下:1、父页面(d...

用原生js在父页面获取iframe子页面的元素,以及在子页面获取父页面元素,这是平时经常会用到的方法,这里写一个例子来总结下:

1、父页面(demo.html),在父页面修改子页面div的背景色为灰色,原来为红色:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>demo主页面</title> <script type="text/javascript"> window.onload = function(){ var _iframe = document.getElementById('iframeId').contentWindow; var _div =_iframe.document.getElementById('objId'); _div.style.backgroundColor = '#ccc'; } </script> </head> <body> <div id='parDiv'>父页面</div> <iframe src="demo-iframe.html" id="iframeId" height="150" width="150"></iframe> </body> </html>

2、子页面(demo-iframe.html),在子页面修改父页面div的字体颜色为红色,原来为黑色:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>子页面demo13-iframe.html</title> <script type="text/javascript"> window.onload = function(){ var _iframe = window.parent; var _div =_iframe.document.getElementById('parDiv'); _div.style.color = 'red'; } </script> </head> <body> <div id='objId'>子页面</div> </body> </html>

3、效果图:

(1)没有加入js时的效果图:

原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法1

(2)加入js后的效果图:

原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法2

以上这篇原生js获取iframe中dom元素--父子页面相互获取对方dom元素的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持查字典教程网。

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类