定義和用法
contentDocument 屬性能夠以 HTML 對象來返回 iframe 中的文檔,可以通過所有標准的 DOM 方法來處理被返回的對象。
語法:frameObject.contentWindow,或者 iframeObject.contentWindow(不是jquery對象)
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].contentWindow.username="zhangsan"; 可以通過這種方式向iframe頁面傳遞參數,在iframe頁面window.username就可以獲取到值,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>
實例:
