iframe.contentWindow属性:关于contentWindow和conten。。。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
iframe.contentWindow属性:关于contentWindow和conten。
定义和⽤法
contentDocument 属性能够以 HTML 对象来返回 iframe 中的⽂档,可以通过所有标准的 DOM ⽅法来处理被返回的对象。
语法:frameObject.contentWindow,或者 iframeObject.contentWindow(不是jquery对象)
⽤iframe嵌套页⾯时,如果⽗页⾯要获取⼦页⾯⾥⾯的内容,可以使⽤contentWindow或者contentDocument,其区别如下:
1、contentWindow 这是个只读属性,返回指定的iframe的窗⼝对象。
它虽然不是标准的⼀部分,但各个主流浏览器都⽀持。
2、contentDocument Firefox ⽀持,IE6,IE7都不⽀持,IE8开始⽀持,需要如此访问 document.frames['J_mainframe'].document。
兼容获取document对象:
var getIFrameDoc = function(){
var iobj = document.createElement("iframe");
document.getElementsByTagName("body")[0].appendChild(iobj);
return iobj.contentDocument || iobj.contentWindow.document;
}
基本使⽤:
1、document.getElementById("myiframe").contentWindow,得到iframe对象后,就可以通过contentWindow得到iframe包含页⾯的window 对象,然后就可以正常访问页⾯元素了;
2、$("#myiframe")[0].contentWindow,jquery选择器获得iframe,先把jquery对象转换为DOM对象,或者使⽤get()⽅法转换;
3、$("#myiframe")[0].contentWindow.$("#dd").val(),可以在得到iframe的window对象后接着使⽤jquery选择器进⾏页⾯操作;
4、$("#myiframe")[0]ername="zhangsan"; 可以通过这种⽅式向iframe页⾯传递参数,在iframe页⾯ername就可以获取到值,username是⾃定义的全局变量;
5、在iframe页⾯通过parent可以获得主页⾯的window,接着就可以正常访问⽗亲页⾯的元素了;
6、parent.$("#frame_A")[0].contentWindow.document.getElmentById("#frame_B"); 同级iframe页⾯之间调⽤,需要先得到⽗亲的window,然后调⽤同级的iframe得到window进⾏操作;
//在⼦级iframe设置⽗级 iframe ,或孙级 iframe ⾼度。
function showIframeH(){
var parentWin = parent.document.getElementById("test");
if(!parentWin) return false;
var sub = parentWin.contentWindow.document.getElementById("test2");
if(!sub) return false;
var thirdHeight = sub.contentWindow.document.body.offsetHeight; //第三层 body 对象
sub.height = thirdHeight; //设置第⼆层 iframe 的⾼度
var secondHeight = parentWin .contentWindow.document.body.offsetHeight; //第⼆层 body 对象
parentWin .height = secondHeight; //设置第⼀层 iframe 的⾼度
}
⼀、在使⽤iframe的页⾯时,要操作这个iframe⾥⾯的DOM元素可以⽤:contentWindow、contentDocument
1、先获取iframe⾥⾯的window对象,再通过这个对象,获取到⾥⾯的DOM元素
例⼦:
var ifr = document.getElementById("iframe");
ifr.contentWindow.document.getElementById("XXXXX")
<iframe src="a.html" id=""></iframe>
ifr.contentWindow 这⾥,返回的是iframe的window对象,所以后⾯可以接着调⽤document⽅法,再接着调⽤
getElementByTagName。
那么就可以对iframe⾥⾯的元素进⾏操作了。
⼆、在iframe本页⾯,要操作这个iframe的⽗页⾯的DOM元素(即嵌套这个iframe的页⾯)可以⽤:
window.parent、window.top(这⾥的TOP是获取的顶层,即有多层嵌套iframe的时候使⽤)
var ifr = document.getElementByTagName("iframe");
ifr.parent.document.getElementById("XXXXX")
<iframe src="a.html" id=""></iframe>
实例:
top.$("iframe[name='iframeWindow']")[0].contentWindow.$("#inside_tableElement"),这样才能获取到iframe⾥的元素, 注意:top.$("iframe[name='iframeWindow']").eq(0).$("#inside_tableElement"),是获取不到的
再可以看看之前写的这篇博客:。