2012-01-12 244 views
2

我在使用javascript在加載時注入iframe的大小時遇到​​問題。我使用大約300px的設置寬度,這很好,但動態地將iframe的高度調整爲其內容大小(博客文章)。在加載後調整iframe的大小

我試着讓contentWindow(沒有孩子dom元素)和contentDocument(這是未定義的)無濟於事。

我這樣做負載:

var iframe = document.createElement('iframe'); 
iframe.setAttribute('id','postFrame'); 
iframe.setAttribute('frameborder','no'); 
iframe.setAttribute('scrolling','no'); 
iframe.setAttribute('onload','resizeFrame();'); 
iframe.setAttribute('width','300px'); 
iframe.setAttribute('src','http://espn.go.com/espn/print?id=7454651'); 
var container = document.getElementById('container'); 
container.appendChild(iframe); 


function resizeFrame(){ /* resize iframe based on content height*/ } 

有沒有辦法基礎上的iframe中的內容重新大小iframe的高度?

*編輯**

可能的解決方法:

是否有希望,我可以使用訪問控制允許來源,以幫助這個問題?可以說iframe中的頁面是我自己的,或者是來自php腳本的echo'd

+0

我假設你不擁有'espn.go.com',在這種情況下,我在這幾個月的工作中做了很多工作 - 它依賴於'客戶'和' 'supplier'(你會是其中之一,espn.go.com會是其中一個)。如果你私下聯繫我,我認爲最好,所以我可以通過Skype與你談談。如果您將Skype用戶名留在此處,我會添加您並嘗試提供幫助。 – ClarkeyBoy 2012-01-12 23:23:31

+0

嗯我不使用skype – mbuff24 2012-01-13 01:19:29

回答

1

我使用以下函數將iframe的大小調整爲內容的高度。它是企業內部網應用程序(只有在IE8正確的測試),但可以肯定的作品,所以可能提供缺少的clue-

function sizeIframeToContent(id) { 
    // resize iframe to be the height of the content 
    try { 
     var frame = document.getElementById(id); 
     innerDoc = (frame.contentDocument) ? 
        frame.contentDocument : frame.contentWindow.document; 
     var objToResize = (frame.style) ? frame.style : frame; 
     objToResize.height = innerDoc.body.scrollHeight + 10 + 'px'; 
     //objToResize.width = innerDoc.body.scrollWidth + 10 + 'px'; 
    } 
    catch (err) { 
     console.log(err.message); 
    } 
} 

編輯的explanation-一旦文件已加載,你應該能夠找到這個文件然後您可以使用它作爲iframe的高度。當你特別詢問高度時,我評論了上述函數的寬度部分。

+0

我在控制檯得到這個:無法讀取屬性'身體'的undefined – mbuff24 2012-01-12 23:27:05

+0

@ buffstar24在Chrome中得到這個以及...將看我能做些什麼 – davidsleeps 2012-01-12 23:27:51

+0

而在Firefox中我獲得許可拒絕 get property HTMLDocument.body – mbuff24 2012-01-12 23:39:36