2013-05-28 25 views
2

我搜索上下,我一直無法找到答案,讓我用下面的代碼來適應頁面的高度:適應100%的高度爲JavaScript控件

// Set path to the iframe file 
var filePath = 'http://www.mysite.com/widget/widget.php'; 
// Setup the iframe target 
var iframe='<iframe id="frame" name="widget" src ="http://www.mysite.com/widget/widget.php" width="100%" height="100%" marginheight="0" marginwidth="0" frameborder="no" scrolling="no"></iframe>'; 
// Write the iframe to the page 
document.write(iframe); 

var myIframe = parent.document.getElementById("frame"); 
// Setup the width and height 
myIframe.height = 450; 
myIframe.width = 255; 

myIframe.src = filePath; 
// set the style of the iframe 
myIframe.style.border = "1px solid #dddddd"; 
myIframe.style.padding = "2px"; 

公告在「myIframe.height = 450;」,限制我的小工具,450個像素高......我需要讓我的小工具來調整到100%,是的,我試過「100%」,這是行不通的。

,當我這個代碼放到它創建了一個簡單的插件網站上面的代碼被拉出。

< SCRIPT LANGUAGE = 「JavaScript的」 SRC = 「http://www.mysite.com/widget/js/javascript-iframe.js」> </SCRIPT>

這裏就是原來的JavaScript的iframe小部件來自:http://papermashup.com/creating-an-iframe-with-javascript/ 但他們沒有關於如何擁有100%身高的說明

+0

您可以使用CSS:'的位置是:絕對/ fixed'並設置'頂部+底部:0'。 – Teemu

+0

@Teemu將是直接加入的iframe作爲一種風格? – antivinegar

+0

只需測試一下。如果它不能正常工作,使用CSS的包裝'div'和'100%''爲iframe'。 – Teemu

回答

3

這對我有用。關鍵是要獲得頁面的分享範圍區域,而不僅僅是高度的高度:這是因爲身體高度遵循內部本身的內容,如果你有一個固定元素的高度,車身高度將永遠不會成爲較小,但大

$(window).resize(function() { 
    //frame height 
    var f = $('#frame').height(); 
    //window visible height <-- height css(height) and other works for the real height, not just the visible 
    var h = window.innerHeight; 
    //give some pixel less to let the iframe fit the screen 
    var something = 5; 
    //if h is less then 450, resize the iframe 
    if (h < 450){ 
     $('#frame').height(h- something); 
     console.log($('#frame').css('height')); 
    }else{ 
     //else, if the iframe height is less then 450, make it bigger 
     if(f<450){ 
      $('#frame').height('450'); 
     } 
    } 
}); 

無論如何,如圖@timo,這是更好地避免使用document.write

+0

請@greycode讓我知道我的解決方案... –

+0

@greycode謝謝誒 –