获取Iframe页面高度并赋值给Iframe以及获取iframe里的元素

最近接手了别人的项目,别人用到了iframe,自己在实战中总结了一些关于iframe的小问题。

获取Iframe页面高度并赋值给Iframe

Html

<iframe name="container_ifranme" id="iframeId" scrolling="no" frameborder="no" border="0" src="home.html" onLoad="iFrameHeight()" ></iframe>

 

Js

function iFrameHeight() {

         var ifm= document.getElementById("iframeId");

                   var subWeb = document.frames ? document.frames["iframeId"].document : ifm.contentDocument;

                   if(ifm != null && subWeb != null) {

                            ifm.style.height = 'auto';//关键这一句,先取消掉之前iframe设置的高度

                            ifm.style.height = subWeb.body.scrollHeight+'px';

                   }

         };

获取iframe里的元素

1,contentWindow:是用来获取子窗口的window对象的,它兼容各大浏览器,用法如下

document.getElementById("iframeId").contentWindow

这样简单的一句就得到了iframe包含页面的window对象;

 

2,contentDocument:是用来获取子窗口的document对象的,主流浏览器都支持和ie8+支持,用法如下

document.getElementById("iframeId").contentDocument

这样简单的一句就得到了iframe包含页面的document对象;

 

以上两种方法是在父窗口中获取到子窗口,既然我们都能拿到子窗口window对象和document对象了,那么子窗口内其他的操作就easy了 !

如果要通过子窗口A访问到同级的子窗口B,那么我们可以在子窗口A中这么来做:

parent.getElementById("iframeId").contentWindow.document.getElmentById("frameId_B") 

或者parent.getElementById("iframeId").contentDocument.getElmentById("frameId_B")就得到B窗口了。

原文地址:https://www.cnblogs.com/ranyonsue/p/10684835.html