1、在父頁面 獲取iframe子頁面的元素
(在同域的情況下 且在http://下測試,且最好在iframe onload加載完畢後 dosomething...)
js寫法
a、同過contentWindow獲取
也有用contentDocument 獲取的 但是contentWindow 兼容各個瀏覽器,可取得子窗口的 window 對象。
contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 對象。
獲取方法
- var frameWin=document.getElementById('iframe').contentWindow; //window對象
- var frameDoc=document.getElementById('iframeId').contentWindow.document //document對象
- var frameBody=document.getElementById('iframeId').contentWindow.document.body //body對象
還有iframe.contentDocument 方法 //但是ie 6,7不支持
b、通過frames[]數組獲取
(但是必須在ifram框架加載完畢後獲取,iframe1是iframe的name屬性)
- document.getElementById('iframId').onload=function(){
- var html= window.frames["name屬性"].document.getElementById('iframe中的元素的id').innerHTML;
- alert(html)
- }
- 如果要獲取iframe中的iframe
- document.getElementById('iframId').onload=function(){
- var html= window.frames["name屬性"].frames["name屬性"].document.getElementById('iframe中的元素的id').innerHTML;
- alert(html)
- }
jq寫法:必須在iframe加載完畢以後纔有效
- a、$("#iframe的ID").contents().find("#iframe中的控件ID").click();//jquery 方法1 必須在iframe加載完後纔有效
- b、$("#iframe中的控件ID",document.frames("frame的name").document)//方法2 <span style="font-family: Arial, Helvetica, sans-serif;">必須在iframe加載完後纔有效</span>
2、在iframe中獲取父級頁面的id元素
(在同域的情況下且在http://下測試,最好是 iframe記載完畢再dosomething)
js寫法:
獲取父級中的objid
- var obj=window.parent.document.getElementById('objId')
jq寫法:
- $('#父級窗口的objId', window.parent.document).css('height':'height); // window可省略不寫
- 或者
- $(window.parent.document).find("#objId").css('height':'height); // window可省略不寫
3、父級窗體訪問iframe中的屬性
(經測試,在ie中最好用原生的onload事件,如果用jq的load把iframe加載完畢 有時候方法調用不到 多刷新纔有效果)
- a、 用contentWindow方法
- document.getElementById('iframe1').onload=function(){
- this.contentWindow.run();
- }
- b、用iframes[]框架集數組方法
- document.getElementById('iframe1').onload=function(){
- frames["iframe1"].run();
- }
===================================
4、在iframe中訪問父級窗體的方法和屬性 //window 可以不寫
- window.parent.attributeName; // 訪問屬性attributeName是在父級窗口的屬性名
- window.parent.Func(); // 訪問屬性Func()是在父級窗口的方法
5、讓iframe自適應高度
- $('#iframeId').load(function() { //方法1
- var iframeHeight = Math.min(iframe.contentWindow.window.document.documentElement.scrollHeight, iframe.contentWindow.window.document.body.scrollHeight);
- var h=$(this).contents().height();
- $(this).height(h+'px');
- });
- $('#iframeId').load(function() { //方法2
- var iframeHeight=$(this).contents().height();
- $(this).height(iframeHeight+'px');
- });
6、iframe的onload的事件,
主流瀏覽器都支持 iframe.onload=function....
在ie下需要用attachEvent綁定事件
7、在iframe所引入的網址寫入防釣魚代碼
if(window!=window.top){
window.top.location.href=window.location.href;
}
window.top.location.href=window.location.href;
}
8、獲取iframe的高度
iframe.contentWindow.document.body.offsetHeight;