最近接手了別人的項目,別人用到了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窗口了。