2012-08-22 52 views
0

我有一個iframe,當內容自動刷新(每隔幾分鐘)或用戶與它交互時,我想調整其大小以匹配其內容。雖然內容在同一個域中,但我很難修改內容。理想情況下,iframe會自動調整其內容的大小。在內容刷新或更新時調整iframe的大小

可調整大小隻有一次電流代碼:

<iframe id="ganglia-frame" src="ganglia.url" width="100%" height="500%"> 
    blah not supported blah 
</iframe> 

<script language="Javascript"> 
    function setIframeHeight(iframe) { 
     if (iframe) { 
      var iframeWin = iframe.contentWindow || 
        iframe.contentDocument.parentWindow; 
      if (iframeWin.document.body) { 
       iframe.height = 
         iframeWin.document.documentElement.scrollHeight || 
         iframeWin.document.body.scrollHeight; 
      } 
     } 
    } 

    $(window).load(function() { 
     setIframeHeight(document.getElementById('ganglia-frame')); 
    }); 
</script> 

相關問題:Adjust width height of iframe to fit with content in it

+0

你看看http://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content,非常全面! –

+0

@DaneBalia如果您指的是接受的答案,它需要修改iframe內容代碼(請參閱第2段),我不能這樣做。 – walrii

回答

0

你需要做的是設置一個計時器,並在一段時間後檢查的iFrame大小。您可能需要檢查幾次,因爲並非所有瀏覽器都立即返回正確的大小。

此方法僅適用於同域iFrames。

將函數綁定到iFrame onload事件,並在執行時檢查iFrame的高度。如果沒有找到身高,可以安排另一次檢查。

var iFrameSizeCount = 0; 
var onloadFunction = function(event){ 
    var contentHeight = document.getElementById('iFrameId').contentWindow.document.body.offsetHeight; 

    if(contentHeight == 0){ 
     // Schedule a recheck in a few moments 
     iFrameSizeCount++; // we keep a count of how many times we loop just in case 
     if(iFrameSizeCount < 10){ // after a while we have to stop checking and call it a fail 
      setTimeout(function(){ onloadFunction(event); }, 200); 
      return false; 
     } 
     else { 
       contentHeight = 100; // eventually if the check fails, default to a fixed height. You could possibly turn scrolling to auto/yes here to give the iFrame scrollbars. 
     } 
    } 
    contentHeight += 30; // add some extra padding (some browsers give a height that's slightly too short) 

    document.getElementById('iFrameId').style.height = contentHeight + 'px'; 
} 

那麼事件綁定到你的iFrame的onload事件(無論你想):

的「滾動=汽車」是很有用的,以防萬一上漿失敗,至少他們有滾動條。如果iFrame重新加載,onload事件會觸發,所以如果點擊了其中的鏈接,就會很有用。

+0

而不是讓身體,得到documentElement,它的利潤率: document.documentElement.offsetHeight + ~~ window.getComputedStyle(document.documentElement中).marginTop.slice(0,-2)+ ~~ window.getComputedStyle( document.documentElement中).marginBottom.slice(0,-2); 其中文檔和窗口實際上是contentWindow和contentWindow.document –

相關問題