AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JavaScript

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

51自学网 http://www.wanshiok.com
原生js,iframe,dom

用原生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' style='width:100px;height:100px;background-color:red;'>子页面</div></body></html>


3、效果图:

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


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

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


原生js,iframe,dom  
上一篇:Angularjs中$http以post请求通过消息体传递参数的实现方法  下一篇:Angularjs使用directive自定义指令实现attribute继承的方法详解