IFrame父页面和子页面的交互

时间:2021-11-25 16:29:16

现在在页面里面用到iframe的情况越来越少了,但有时还是避免不了,甚至这些页面之间还需要用js来做交互,那么这些页面如何操作彼此的dom呢?下面将会逐步介绍。

1.父页面操作子页面里面的dom

下面提供了四中方法来操作iframe里面的dom:

a. contentWindow: 以window对象返回iframe中的文档,所有主流浏览器都支持。

用法:

// 获取id为iframeId的子页面中的div01元素
document.getElementById('iframeId').contentWindow.document.getElementById('div01')

b. contentDocument: 以document对象返回iframe中的文档,IE8以下浏览器不支持,IE8以下可以由contentWindow替代。

用法:

// 获取id为iframeId的子页面中的div02元素
document.getElementById('iframeId').contentDocument.getElementById('div02')

c. window.frames[iframeName]: 通过iframe的name属性获取iframe的内容

用法:

// 获取name为iframeName的子页面中的div01元素
window.frames['iframeName'].document.getElementById('div01')

d. window.frames[iframeIndex]: 通过iframe在页面中的索引值获取iframe的内容

// 获取iframe索引值为0的子页面中的div01元素
window.frames[0].document.getElementById('div01')

2.子页面操作父页面里面的dom

子页面操作父页面的dom可以通过window.parent或者window.top来实现,parent代表父页面,top代表最*页面。

用法:

// 获取父页面中id为menu的元素,window.parent可简写为parent
window.parent.document.getElementById('menu')

Ok,以上就是关于iframe父子页面之间dom操作的一些内容,如果需要进一步了解可以参考示例:

示例地址:http://wangchi.github.io/blogdemos/2015/01/js-iframe-dom/js-iframe-dom.html

源码:https://github.com/wangchi/wangchi.github.io/tree/master/blogdemos/2015/01/js-iframe-dom