关于contentWindow和contentDocument

   用iframe嵌套页面是,如果父页面要获取子页面里面的内容,可以使用contentWindow或者contentDocument,其区别如下:

a>contentWindow  这是个只读属性,返回指定的iframe的窗口对象。它虽然不是标准的一部分,但各个主流浏览器都支持。

b>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].contentWindow.username="zhangsan"; 可以通过这种方式向iframe页面传递参数,在iframe页面window.username就可以获取到值,username是自定义的全局变量;

5)在iframe页面通过parent可以获得主页面的window,接着就可以正常访问父亲页面的元素了;

7)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  =  x.contentWindow.document.body.offsetHeight;  // 第二层 body 对象
    x.height  =  secondHeight;  // 设置第一层 iframe 的高度
     // alert(secondHeight);
     // alert('body: ' + x.contentDocument.body.offsetHeight + ' div:' + thirdHeight);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值