2016-09-05 91 views
0

我有一個Iframe,並且此iframe的內容發生更改,因此窗口可以更大或更小,因此我添加了自動調整大小腳本。自動調整大小不工作

這個腳本完美地工作,但只有當內容更大時,如果內容改變並且比上一次更小,窗口不會調整大小和heigth是相同的。

我不知道什麼是錯的。如果你有任何想法會很好。

也有我的劇本,我的iframe:

function autoResize(id){ 
    var newheight; 
    var newwidth; 

    if(document.getElementById){ 
     newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; 
     newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth; 
    } 

    document.getElementById(id).height=(newheight) + "px"; 
    document.getElementById(id).width=(newwidth) + "px"; 
} 

$(function(){ 
    var f=$('#foo') 
    f.load(function(){ 
     f.contents().find("body").on('click', function(event) { 
      runAfterTimeout('foo'); 
     }); 
    }) 
}) 
function runAfterTimeout(id) { 
    setTimeout(function(){ 
     autoResize(id); 
    },1000); 
}; 

我的IFRAME:

<iframe height="300px" width="100%" id="foo" src="" style="border: 0px currentColor; border-image: none;" onload="autoResize('foo')"></iframe> 
+0

也許是因爲高度不得小於300像素默認情況下,嘗試刪除height屬性,並通過在CSS中添加最小高度爲#foo更換。如果它不會幫助 - 在plunkr或其他服務中創建一個代碼片段 – booboos

回答

1

我認爲你需要重新設置的iframe每次onload事件被稱爲的高度。試試這個:

function autoResize(id){ 
    document.getElementById(id).height="0px"; 
    var newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; 
    var newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth; 

    document.getElementById(id).height=(newheight) + "px"; 
    document.getElementById(id).width=(newwidth) + "px"; 
}