JS操作iframe里的dom(转)

一、父级窗口操作iframe里的dom

JS操作iframe里的dom可是使用contentWindow属性,contentWindow属性是指指定的frame或者iframe所在的window对象,在IE中iframe或者frame的contentWindow属性可以省略,但在Firefox中如果要对iframe对象进行编辑则,必须指定contentWindow属性,contentWindow属性支持所有主流浏览器

相关的还有一个contentDocument属性,这个属性是指指定的frame或者iframe所在的document对象,但是悲剧的是,ie6-ie7并不支持这个属性。

ie6和ie7还可以使用document.frames["iframe Name"]或者document.frames["iframe ID"]来获取相当于contentWindow属性,而firefox和chrome并不支持这些document.frames["iframe Name"]或者document.frames["iframe ID"],但是window.frames["iframe Name"]或window.frames[index](index是索引值)也支持所有主流浏览器

我们知道document对象是window对象的一个子对象,所以我们可以通过document.getElementById(“iframe ID”).contentWindow.document来获取iframe的document对象,相当于contentDocument属性。

二、iframe里的js操作父级窗口的dom

iframe里的js要操作父级窗口的dom,必须搞懂几个对象:

parent是父窗口(如果窗口是顶级窗口,那么parent==self==top),

top是最顶级父窗口(有的窗口中套了好几层frameset或者iframe),

self是当前窗口(等价window),

opener是用open方法打开当前窗口的那个窗口;

这样iframe里的js要操作父级窗口的dom可以通过parent,top这些对象来获取父窗口的window对象,例如:

parent.document.getElementById(“dom ID”);

parent,top还能调用父级窗口的的js方法,比如,getIFrameDOM(iID)是父级窗口的一个方法,那么iframe里可以使用parent.getIFrameDOM(“wIframeA”)来调用父级窗口的getIFrameDOM(iID)方法;

//兼容IE、Firefox的iframe DOM获取函数

function getIFrameDOM(id)

{

        return document.getElementById(id).contentDocument|| document.frames[id].document;
}

、iframeA里的js操作iframeB的dom

parent.getIFrameDOM("iframeB");

原文地址:https://www.cnblogs.com/zhwl/p/2092196.html