适应javascript小部件100%的高度

时间:2013-05-28 18:34:08

标签: javascript iframe widget

我上下搜索过,我无法找到允许我使用以下代码调整页面高度的答案:

// 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%”,它将无法正常工作。

当我将此代码放到创建简单小部件的网站上时,会拉出上面的代码。

&LT; script language =“JavaScript”src =“http://www.mysite.com/widget/js/javascript-iframe.js”&gt;&lt; / script&gt;

以下是原始javascript iframe小部件的来源:http://papermashup.com/creating-an-iframe-with-javascript/ 但他们没有关于如何获得100%身高的说明

1 个答案:

答案 0 :(得分: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