js獲取iframe中的元素以及在iframe中獲取父級的元素(包括iframe中不存在name和id的情況)


 
第一種情況:iframe中不存在name和id的方法:(通過contentWindow獲取)
var iframe = document.getElementsByTagName('iframe')[0];
var ifr_document = iframe.contentWindow.document;//iframe中的文檔內容
或者:
var _iframe = document.getElementByIdx_x('iframeId').contentWindow;  
var _div =_iframe.document.getElementByIdx_x('objId'); 
或者:
  1. var frameWin=document.getElementById('iframe').contentWindow;    //window對象  
  2. var frameDoc=document.getElementById('iframeId').contentWindow.document  //document對象  
  3. var frameBody=document.getElementById('iframeId').contentWindow.document.body   //body對
第二種情況:iframe中存在name或者id的方法:(通過frames[]數組獲取)
document.frames['iframe的name'].document.getElementById('元素的ID');
第三種情況:在iframe中獲取父級頁面的id元素 :
var  obj=window.parent.document.getElementById('objId') ;
$(window.parent.document).find("#objId").css('height':'height);   // window可省略不寫 jquery
 
第四種情況:父級窗體訪問iframe中的屬性
  1. a、 用contentWindow方法   
  2. document.getElementById('iframe1').onload=function(){  
  3.          this.contentWindow.run();  
  4.  }  
  5. b、用iframes[]框架集數組方法  
  6. document.getElementById('iframe1').onload=function(){  
  7.          frames["iframe1"].run();  
第五種情況:在iframe中訪問父級窗體的方法和屬性 //window 可以不寫
  1. window.parent.attributeName;  // 訪問屬性attributeName是在父級窗口的屬性名  
  2. window.parent.Func();  // 訪問屬性Func()是在父級窗口的方法 
 
第五種情況:讓iframe自適應高度
  1. $('#iframeId').load(function() { //方法1  
  2.     var iframeHeight = Math.min(iframe.contentWindow.window.document.documentElement.scrollHeight, iframe.contentWindow.window.document.body.scrollHeight);  
  3.     var h=$(this).contents().height();  
  4.     $(this).height(h+'px');   
  5. });  
  6.   
  7. $('#iframeId').load(function() { //方法2  
  8.     var iframeHeight=$(this).contents().height();  
  9.     $(this).height(iframeHeight+'px');   
  10. }); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM