您的位置:首页 > 其它

父子页面(iframe)相互获取对方dom元素

2016-10-29 00:07 197 查看
现在iframe的使用虽然开始越来越少,但是还是有牵涉到iframe的使用情况,特别是多个iframe互相嵌套,又要进行获取的情况。

现在整理了父子iframe之间互相获取的方式。

(1)父页面获取子页面的方式。

主要通过:

iframe的contentWindow属性,代表iframe所在的window对象。


示例如下:

<script type="text/javascript">
window.onload = function(){
var cWindow = document.getElementById('iframeId').contentWindow;
var div=cWindow .document.getElementById('divId');
//some other operation
}

</script>

....

<iframe id="iframeId" src="iframe.html" width="100" height="100">
<div id="divId"></div>
</iframe>


(2) 通过子元素获取父元素

主要通过 window.parent 进行获取


示例代码如下:

<div id-"pDivId"></div>
<iframe src="iframe.html" width="100" height="100">

</iframe>


iframe.html页面中的内容为(实现对父元素的操作):

<script type="text/javascript">
window.onload = function(){
var pWindow= window.parent;
var pDiv=pWindow.document.getElementById('pDivId');
//some other operation
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: